Android toolbar center title and custom font - android
I'm trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).
At the moment, i'm using the good old ActionBar, and I was setting the title to empty value, and using setCustomView to put my custom font TextView and center it using ActionBar.LayoutParams.
Is there a better way to do that? Using the new Toolbar as my ActionBar.
To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?android:attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
This's just to help to join all pieces using #MrEngineer13 answer with #Jonik and #Rick Sanchez comments with the right order to help to achieve title centered easly!!
The layout with TextAppearance.AppCompat.Widget.ActionBar.Title :
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
The way to achieve with the right order:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
mTitle.setText(toolbar.getTitle());
getSupportActionBar().setDisplayShowTitleEnabled(false);
Please don't forget to upvote #MrEngineer13 answer !!!
Here is a sample project ToolbarCenterTitleSample
Hope to help somebody else ;)
The ToolBar title is stylable. Any customization you make has to be made in the theme. I'll give you an example.
Toolbar layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
style="#style/ToolBarStyle.Event"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="#dimen/abc_action_bar_default_height_material" />
Styles:
<style name="ToolBarStyle" parent="ToolBarStyle.Base"/>
<style name="ToolBarStyle.Base" parent="">
<item name="popupTheme">#style/ThemeOverlay.AppCompat.Light</item>
<item name="theme">#style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
<style name="ToolBarStyle.Event" parent="ToolBarStyle">
<item name="titleTextAppearance">#style/TextAppearance.Widget.Event.Toolbar.Title</item>
</style>
<style name="TextAppearance.Widget.Event.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<!--Any text styling can be done here-->
<item name="android:textStyle">normal</item>
<item name="android:textSize">#dimen/event_title_text_size</item>
</style>
we don't have direct access to the ToolBar title TextView so we use reflection to access it.
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(mToolBar);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
Define the following class:
public class CenteredToolbar extends Toolbar {
private TextView centeredTitleTextView;
public CenteredToolbar(Context context) {
super(context);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setTitle(#StringRes int resId) {
String s = getResources().getString(resId);
setTitle(s);
}
#Override
public void setTitle(CharSequence title) {
getCenteredTitleTextView().setText(title);
}
#Override
public CharSequence getTitle() {
return getCenteredTitleTextView().getText().toString();
}
public void setTypeface(Typeface font) {
getCenteredTitleTextView().setTypeface(font);
}
private TextView getCenteredTitleTextView() {
if (centeredTitleTextView == null) {
centeredTitleTextView = new TextView(getContext());
centeredTitleTextView.setTypeface(...);
centeredTitleTextView.setSingleLine();
centeredTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
centeredTitleTextView.setGravity(Gravity.CENTER);
centeredTitleTextView.setTextAppearance(getContext(), R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
Toolbar.LayoutParams lp = new Toolbar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
centeredTitleTextView.setLayoutParams(lp);
addView(centeredTitleTextView);
}
return centeredTitleTextView;
}
}
...and then just use it instead of regular Toolbar like this:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent">
<your.packagename.here.CenteredToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/reset_password_page_title"/>
<!-- Other views -->
</RelativeLayout>
You still need these 2 lines of code in your Activity (as with standard Toolbar):
Toolbar toolbar = (Toolbar) findViewByid(R.id.toolbar); // note that your activity doesn't need to know that it is actually a custom Toolbar
setSupportActionBar(binding.toolbar);
That's it! You don't need to hide the standard left-aligned title, don't need to duplicate the same XML code over and over, etc., just use CenteredToolbar like if it was default Toolbar. You can also set your custom font programatically since you now have direct access to the TextView. Hope this helps.
MaterialToolbar from Material Components 1.4.0-alpha02 now has the ability to center the toolbar's title by setting the titleCentered attribute to true:
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
style="#style/Widget.MaterialComponents.Toolbar.Primary"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
</com.google.android.material.appbar.AppBarLayout>
Here is title text dependant approach to find TextView instance from Toolbar.
public static TextView getToolbarTitleView(ActionBarActivity activity, Toolbar toolbar){
ActionBar actionBar = activity.getSupportActionBar();
CharSequence actionbarTitle = null;
if(actionBar != null)
actionbarTitle = actionBar.getTitle();
actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
if(TextUtils.isEmpty(actionbarTitle)) return null;
// can't find if title not set
for(int i= 0; i < toolbar.getChildCount(); i++){
View v = toolbar.getChildAt(i);
if(v != null && v instanceof TextView){
TextView t = (TextView) v;
CharSequence title = t.getText();
if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title) && t.getId() == View.NO_ID){
//Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
//in same manner subtitle TextView can be obtained.
return t;
}
}
}
return null;
}
No one has mentioned this, but there are some attributes for Toolbar:
app:titleTextColor for setting the title text color
app:titleTextAppearance for setting the title text appearance
app:titleMargin for setting the margin
And there are other specific-side margins such as marginStart, etc.
I use this solution:
static void centerToolbarTitle(#NonNull final Toolbar toolbar) {
final CharSequence title = toolbar.getTitle();
final ArrayList<View> outViews = new ArrayList<>(1);
toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
if (!outViews.isEmpty()) {
final TextView titleView = (TextView) outViews.get(0);
titleView.setGravity(Gravity.CENTER);
final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
toolbar.requestLayout();
//also you can use titleView for changing font: titleView.setTypeface(Typeface);
}
}
Without toolbar TextView we can customize font by using below code
getSupportActionBar().setDisplayShowTitleEnabled(false);
or
getActionBar().setDisplayShowTitleEnabled(false);
public void updateActionbar(String title){
SpannableString spannableString = new SpannableString(title);
spannableString.setSpan(new TypefaceSpanString(this, "futurastdmedium.ttf"),
0, spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mToolbar.setTitle(spannableString);
}
public class TestActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
customizeToolbar(toolbar);
}
public void customizeToolbar(Toolbar toolbar){
// Save current title and subtitle
final CharSequence originalTitle = toolbar.getTitle();
final CharSequence originalSubtitle = toolbar.getSubtitle();
// Temporarily modify title and subtitle to help detecting each
toolbar.setTitle("title");
toolbar.setSubtitle("subtitle");
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView textView = (TextView) view;
if(textView.getText().equals("title")){
// Customize title's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
textView.setTypeface(typeface);
} else if(textView.getText().equals("subtitle")){
// Customize subtitle's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
textView.setTypeface(typeface);
}
}
}
// Restore title and subtitle
toolbar.setTitle(originalTitle);
toolbar.setSubtitle(originalSubtitle);
}
}
Layout:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
Code:
Toolbar mToolbar = parent.findViewById(R.id.toolbar_top);
TextView mToolbarCustomTitle = parent.findViewById(R.id.toolbar_title);
//setup width of custom title to match in parent toolbar
mToolbar.postDelayed(new Runnable()
{
#Override
public void run ()
{
int maxWidth = mToolbar.getWidth();
int titleWidth = mToolbarCustomTitle.getWidth();
int iconWidth = maxWidth - titleWidth;
if (iconWidth > 0)
{
//icons (drawer, menu) are on left and right side
int width = maxWidth - iconWidth * 2;
mToolbarCustomTitle.setMinimumWidth(width);
mToolbarCustomTitle.getLayoutParams().width = width;
}
}
}, 0);
A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:
Add to styles.xml:
<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">16sp</item>
<item name="android:textColor">#FF202230</item>
<item name="android:fontFamily">#font/varela_round_regular</item>
</style>
In your res folder create a font folder (Ex: varela_round_regular.ttf)
Read the official guide to find out more https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
Solution that I used for this problem:
public static void applyFontForToolbarTitle(Activity a){
Toolbar toolbar = (Toolbar) a.findViewById(R.id.app_bar);
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView tv = (TextView) view;
if(tv.getText().equals(a.getTitle())){
tv.setTypeface(getRuneTypefaceBold(a));
break;
}
}
}
}
For center gravity I think it would be necessary to change layout params to match_parent horizontally and then:
tv.setGravity(Gravity.CENTER);
I don't know if anything changed in the appcompat library but it's fairly trivial, no need for reflection.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// loop through all toolbar children right after setting support
// action bar because the text view has no id assigned
// also make sure that the activity has some title here
// because calling setText() with an empty string actually
// removes the text view from the toolbar
TextView toolbarTitle = null;
for (int i = 0; i < toolbar.getChildCount(); ++i) {
View child = toolbar.getChildAt(i);
// assuming that the title is the first instance of TextView
// you can also check if the title string matches
if (child instanceof TextView) {
toolbarTitle = (TextView)child;
break;
}
}
I solved this solution , And this is a following codes:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order History"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/colorWhite"
/>
</android.support.v7.widget.Toolbar>
And you can change title/label , in Activity, write a below codes:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
mTitle.setText("#string/....");
You can use like the following
<android.support.v7.widget.Toolbar
android:id="#+id/top_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppThemeToolbar">
<TextView
android:id="#+id/pageTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
With the Material Components, starting from the version 1.4.x as described in the doc you can use the MaterialToolbar.
Just add the attribute app:titleCentered and/or app:subtitleCentered attributes to true on your MaterialToolbar.
Something like:
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
app:titleCentered="true"
... />
With Compose using the Material3 package you can simply use the CenterAlignedTopAppBar:
CenterAlignedTopAppBar(
title = { Text("Centered TopAppBar") },
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
}
)
If you are using Compose and the Material2 package, there isn't a builtin component but you can customize the layout of content inside the TopAppBar as described in this answer.
Update from #MrEngineer13's answer: to align title center in any cases, including Hamburger icon, option menus, you can add a FrameLayout in toolbar like this:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="#+id/toolbar_title" />
</FrameLayout>
</android.support.v7.widget.Toolbar>
Now using Material Design 3 we can align the title in the center without doing extra work or without adding a text view in the toolbar
Added below dependencies in build.gradle file
implementation 'com.google.android.material:material:1.6.1'
To align the title in the center We need to use the below properly
app:titleCentered="true"
To align subtitles in the center we need to use the below property
app:subtitleCentered="true"
Sample Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="AskNilesh"
app:subtitle="Nilesh"
app:subtitleCentered="true"
app:menu="#menu/top_app_bar"
app:titleCentered="true"
app:navigationIcon="#drawable/ic_android_black_24dp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
OUTPUT
Even though adding a text view to the toolbar can solve the problem of the restriction of title styling, there is an issue with it. Since we are not adding it to a layout, we do not have too much control over its width. We can either use wrap_content or match_parent.
Now consider a scenario where we have a searchView as a button on the right edge of the toolbar. If the title contents are more, it will go on top of the button obscuring it. There is no way of controlling this short of setting a width to the label and is something you don't want to do if you want to have a responsive design.
So, here is a solution that worked for me which is slightly different from adding a textview to the toolbar. Instead of that, add the toolbar and text view to a relative layout and ensure that the text view is on top of the toolbar. Then we can use appropriate margins and make sure the text view shows up where we want it to show up.
Make sure you set the toolbar to not show the title.
Here is the XML for this solution:
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
<android.support.v7.widget.Toolbar
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:id="#+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:titleTextAppearance="#style/AppTheme.TitleTextView"
android:layout_marginRight="40dp"
android:layoutMode="clipBounds">
<android.support.v7.widget.SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:foregroundTint="#color/white" />
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="90dp"
android:text="#string/app_name"
android:textSize="#dimen/title_text_size"
android:textColor="#color/white"
android:lines="1"
android:layout_marginLeft="72dp"
android:layout_centerVertical="true" />
</RelativeLayout>
Solves the issue #ankur-chaudhary mentioned above.
Since android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font without external textview.
create new style in styles.xml
<style name="RobotoBoldTextAppearance">
<item name="android:fontFamily">#font/roboto_condensed_bold</item>
</style>
and use it
mToolbar.setTitleTextAppearance(this, R.style.RobotoBoldTextAppearance);
I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.
At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):
class CenteredToolbar #JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: Toolbar(context, attrs, defStyleAttr) {
init {
addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val titleTextView = findViewById<TextView>(R.id.centerTitle)
val x = titleTextView.x.toInt()
val x2 = x + titleTextView.width
val fullWidth = width
val fullCenter = fullWidth / 2
val offsetLeft = Math.abs(fullCenter - x)
val offsetRight = Math.abs(x2 - fullCenter)
val differOffset = Math.abs(offsetLeft - offsetRight)
if (offsetLeft > offsetRight) {
titleTextView.setPadding(differOffset, 0, 0, 0)
} else if (offsetRight > offsetLeft) {
titleTextView.setPadding(0, 0, differOffset, 0)
}
removeOnLayoutChangeListener(this)
}
})
}
override fun setTitle(resId: Int) = getTitleView().setText(resId)
override fun setTitle(title: CharSequence?) = getTitleView().setText(title)
fun getTitleView(): TextView = findViewById(R.id.centerTitle)
}
Secondly, you need create layout toolbar:
<CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar">
<TextView
android:id="#+id/centerTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</CenteredToolbar>
That's all
Try taking Toolbar and tittle in a separate view. Take a view on right end and given them weight equal to the toolbar weight. In this way your tittle will come in center.
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#color/white_color">
<LinearLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white_color">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="#color/white_color"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:layout_weight="0.2"
app:contentInsetStartWithNavigation="0dp"
app:navigationIcon="#color/greyTextColor">
</android.support.v7.widget.Toolbar>
<com.an.customfontview.CustomTextView
android:id="#+id/headingText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center"
android:text="Heading"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/keyboard_number"
android:layout_gravity="center_horizontal|center_vertical"
app:textFontPath="fonts/regular.ttf" />
<ImageView
android:id="#+id/search_icon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:layout_weight="0.2"
android:layout_gravity="center_horizontal|center_vertical"
android:src="#drawable/portfolio_icon"/>
</LinearLayout>
</android.support.design.widget.AppBarLayout>
You can insert this code in your xml file
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:textColor="#000000"
android:textSize="20dp"
android:id="#+id/toolbar_title" />
</androidx.appcompat.widget.Toolbar>
To use a custom title in your Toolbar you can add a custom title like :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="5dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:id="#+id/lnrTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/txvHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center"
android:gravity="center"
android:ellipsize="end"
android:maxLines="1"
android:text="Header"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Java Code:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() == null)
return;
getSupportActionBar().setTitle("Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Use com.google.android.material.appbar.MaterialToolbar and app:titleCentered="true" tag
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
private void makeTitleCenter(String title, Toolbar toolbar) {
if (title != null && !TextUtils.isEmpty(title.trim())) {
final String tag = " ";
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(tag);
}
TextView titleTv = null;
View leftBtn = null;
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
CharSequence text = null;
if (view instanceof TextView && (text = ((TextView) view).getText()) != null && text.equals(tag)) {
titleTv = (TextView) view;
} else if (view instanceof ImageButton) {
leftBtn = view;
}
}
if (titleTv != null) {
final TextView fTitleTv = titleTv;
final View fLeftBtn = leftBtn;
fTitleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
fTitleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int leftWidgetWidth = fLeftBtn != null ? fLeftBtn.getWidth() : 0;
fTitleTv.setPadding(DimenUtil.getResources().getDisplayMetrics().widthPixels / 2 - leftWidgetWidth - fTitleTv.getWidth() / 2, 0, 0, 0);
fTitleTv.requestLayout();
}
});
}
}
}
for custom font in toolbar you can override textView font in style and then every textView in your app also toolbar title font changed automatically
i tested it in android studio 3.1.3
in style do it:
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
<item name="android:fontFamily">#font/your_custom_font</item>
</style>
and then in your theme use this:
<item name="android:textViewStyle">#style/defaultTextViewStyle</item>
I found another way to add custom toolbar without any adicional Java/Kotlin code.
First: create a XML with your custom toolbar layout with AppBarLayout as the parent:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginEnd="#dimen/magin_default"
android:src="#drawable/logo" />
</android.support.v7.widget.Toolbar>
Second: Include the toolbar in your layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
tools:context=".app.MainAcitivity"
tools:layout_editor_absoluteY="81dp">
<include
layout="#layout/toolbar_inicio"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Put your layout here -->
</android.support.constraint.ConstraintLayout>
Related
Android Searchview back button color change
How to change the color of black arrow(Back button) in searchview I have tried by customizing with below code ImageView backid = (ImageView) searchViewAndroidActionBar.findViewById(R.id.search_button); backid.setColorFilter(ContextCompat.getColor(Shopping_CategoriesCommon.this, R.color.white), PorterDuff.Mode.SRC_IN); backid.setImageResource(R.drawable.search); but it doesn't work
Add this attribute to your toolbar in xml file app:collapseIcon <android.support.v7.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="#dimen/toolbarHeight" app:collapseIcon="#drawable/collapseBackIcon" />
After a day search i resolved it by adding app:collapseIcon="#drawable/back_arrow" to the custom toolbar <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#color/colorPrimary" android:orientation="vertical" app:collapseIcon="#drawable/back_arrow"/>
I could change the color using Reflection. try { final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); Field mCollapseIcon = toolbar.getClass().getDeclaredField("mCollapseIcon"); mCollapseIcon.setAccessible(true); Drawable drw = (Drawable) mCollapseIcon.get(toolbar); drw.setTint(color); } catch (Exception e) { }
How to align action bar title to centre without using custom view
I want to align the action bar title to centre without the help of custom view . I would appreciate any help. Without using the custom view, modifying only default action bar title
You can align the title to the center when you use ActionBar, but you can use Toolbar to do this. Toolbar is more useful and easier than ActionBar, you can use this layout to define the center title TextView for you activity: <android.support.v7.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="40dip"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="#string/app_name" /> </android.support.v7.widget.Toolbar> And use this code for a back button: protected void onCreate(#Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_toolbar); Toolbar toolbar = (Toolbar) findViewById(R.id.single_toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if(actionBar != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); } #Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } You also need to override onCreateOptionsMenu method for the menu, and you can refer to this project : chrisbanes/cheesesquare.
Ok, You can try this: <android.support.v7.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" > <TextView android:textColor="#fff" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_gravity="center" android:text="#string/app_name" /> </android.support.v7.widget.Toolbar> And remember to add this line in your activity's java code: getSupportActionBar.setTitle("");
It seems there is no way to do this without custom view. You can get the title view: View decor = getWindow().getDecorView(); TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android")); But changing of gravity or layout_gravity doesn't have an effect. The problem in the ActionBarView, which layout its children by itself so changing of layout params of its children also doesn't have an effect. To see this excecute following code: ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android")); View v = actionBar.getChildAt(0); ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); p.gravity= Gravity.CENTER; v.setLayoutParams(p); v.setBackgroundColor(Color.BLACK);
Issue with setting android's appBar/toolbar title multiple times
I'm developing an android app and I'm stuck in organizing the layout in a input form activity. I would like to organize the layout of my activity like this sample (found in google android's docs): https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bzhp5Z4wHba3Skg2b19UVS1LSmc/components_textfields_labels2.png . So a big app bar will contain one or two text field, referencing the name and the description of a user's activity, and within the activity layout's content the rest of input controls. The behaviour I would reach is: the activity title is initially empty and toolbar collapsed when I get down the toolbar the text input appear and the user insert some text when the user collapse the toolbar, the activity title (that is, the toolbar title) must be set to the input text value The problem is that only one time this mechanism works: once set value and collapse the toolbar, when I get down again the toolbar, set the text input value and collapse the toolbar, the title is not setted, that is, setTitle has no effect over the first time. I will now list my code: I tried to use a custom app bar layout, a collapsing tool bar layout, a toolbar and a text input in the following way: <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" tools:context="com.example.davide.inputformapp.MainActivity"> <com.example.davide.inputformapp.MyAppBarLayout.MyAppBarLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="#+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="400dp" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginEnd="#dimen/activity_horizontal_margin" app:expandedTitleMarginStart="#dimen/activity_horizontal_margin" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <android.support.v7.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="parallax" app:popupTheme="#style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TextInputEditText android:id="#+id/textInput" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.design.widget.CollapsingToolbarLayout> </com.example.davide.inputformapp.MyAppBarLayout.MyAppBarLayout> </android.support.design.widget.CoordinatorLayout> where MyAppBarLayout is the class defined in this way(the code is not mine, I found here in a stackoverflow discussion): public class MyAppBarLayout extends AppBarLayout implements AppBarLayout.OnOffsetChangedListener { private State state; private OnStateChangeListener onStateChangeListener; public MyAppBarLayout(Context context) { super(context); } public MyAppBarLayout(Context context, AttributeSet attrs) { super(context, attrs); } #Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!(getLayoutParams() instanceof CoordinatorLayout.LayoutParams) || !(getParent() instanceof CoordinatorLayout)) { throw new IllegalStateException( "MyAppBarLayout must be a direct child of CoordinatorLayout."); } addOnOffsetChangedListener(this); } #Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset == 0) { if (onStateChangeListener != null && state != State.EXPANDED) { Log.d("MYAPP","---> EXPANDED"); onStateChangeListener.onStateChange(State.EXPANDED); } state = State.EXPANDED; } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) { if (onStateChangeListener != null && state != State.COLLAPSED) { Log.d("MYAPP","---> COLLAPSED"); onStateChangeListener.onStateChange(State.COLLAPSED); } state = State.COLLAPSED; } else { if (onStateChangeListener != null && state != State.IDLE) { Log.d("MYAPP","---> IDLE"); onStateChangeListener.onStateChange(State.IDLE); } state = State.IDLE; } } public void setOnStateChangeListener(OnStateChangeListener listener) { this.onStateChangeListener = listener; } public interface OnStateChangeListener { void onStateChange(State toolbarChange); } public enum State { COLLAPSED, EXPANDED, IDLE } } The code in the main activity's onCreate() method is: toolbar = (Toolbar) findViewById(R.id.toolbar); textInput = (TextInputEditText) findViewById(R.id.textInput); final MyAppBarLayout collapsableAppBar = (MyAppBarLayout) findViewById(R.id.appbar); setSupportActionBar(toolbar); setTitle(null); collapsableAppBar.setOnStateChangeListener(new MyAppBarLayout.OnStateChangeListener() { #Override public void onStateChange(MyAppBarLayout.State toolbarChange) { String value = textInput.getText().toString(); toolbar.setTitle(value); } }); Any suggestion? Thanks, davide
set "android:id" to CollapsingToolbarLayout. find it in activity and set title to it. I have tried many answers but only setting title to CollapsingToolbarLayout worked.
Please try to replace toolbar.setTitle(value) with getSupportActionBar().setTitle(value) as mentioned in this answer
You have to change title like this : instead of toolbar.setTitle(value); do getSupportActionBar.setTitle(value); on setOnStateChangeListener
it may not be a good solution but one way to get every thing working is by creating custom action Bar custom_actionbar.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="100dp" android:background="#drawable/yourcolorforactionbar" > <TextView android:id="#+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textAllCaps="true" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#fff" android:textStyle="bold" /> <ImageView android:id="#+id/myimage" android:layout_width="20dp" android:layout_height="20dp" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="8dp" android:src="#drawable/yourimagetoset" /> <ImageButton android:id="#+id/imageButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="8dp" android:background="#null" android:src="#android:drawable/menubutoon" /> </RelativeLayout> mainactivity.class public class MainActivity extends Activity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar mActionBar = getActionBar(); mActionBar.setDisplayShowHomeEnabled(false); mActionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text); mTitleTextView.setText("My Own Title"); ImageButton imageButton = (ImageButton) mCustomView .findViewById(R.id.imageButton); imageButton.setOnClickListener(new OnClickListener() { #Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Refresh Clicked!", Toast.LENGTH_LONG).show(); } }); mActionBar.setCustomView(mCustomView); mActionBar.setDisplayShowCustomEnabled(true); } }
Hiding Scrolling activity title in android studio
I have created a Scrolling activity. I want to hide this activity title (Banglalink Latest Offers). But I want to show activity title at this stage (Banglalink Latest Offers). Is it possible to do? If yes, how?
A bit late but I think this might help someone looking for a solution for this, you can simply set the text color to transparent. Just add the below style to your styles.xml: <style name="ToolBarTheme"> <item name="android:textColor">#android:color/transparent</item> </style> and add the following attribute to your CollapsingToolbarLayout: app:expandedTitleTextAppearance="#style/ToolBarTheme"
Simply add this line to CollapsingToolbarLayout in your xml file: app:titleEnabled="false"
Your best bet it to convert to a normal activity (with a scrollview as a child), start with the actionbar hidden (using the hide() call below (put it inside onCreate()). Then put the coloured backgroiund at top of screen inside scrollview. Finally, you can programmatically toggle between hiding your title (and actionbar), but showing your header background (or vice versa) when needed by adding a horizontal scroll listener/observer. The listener will toggle the actionbar and header view depending on how far the user has scrolled down. E.g: Add observer inside onStart(): hsv.getViewTreeObserver().addOnScrollChangedListener( new ViewTreeObserver.OnScrollChangedListener() { #Override public void onScrollChanged() { Log.i(TAG,"scroll:"+hsv.getScrollX());}}); // todo adjust scrollx value to decide on hide or show call: if (hsv.getScrollX() > 100) getActionBar().show(); mHeaderLayoutView.setVisibility(View.GONE); else getActionBar().hide(); mHeaderLayoutView.setVisibily(View.VISIBLE) ... Note: hsv is a HorizontalScrollView works. Note, if your are using the support libraries (E.g. you activity class extends AppCompatActivity), the code would change to: getSupportActionBar().hide(); Im not sure if the getScrollX is in pixels or dp (job for you to research). Hope this helps!
<resources> <dimen name="app_bar_height">180dp</dimen> <dimen name="fab_margin">16dp</dimen> <dimen name="text_margin">16dp</dimen> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="appbar_padding_top">8dp</dimen> </resources> This must be your dimens.xml file. If you reduce the app_bar_height to 120dp or close... the text will be invisible. I dont know how to bring it back after collapse
This is working for me: CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout); toolbarLayout.setTitle(" ");
You have to remove the line android:theme="#style/AppTheme.AppBarOverlay"in your XML. Once you removed the title will go to background. So you able hide title of the activity. as an example, you can place a placeholder to hide it. <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="#+id/app_bar" android:layout_width="match_parent" android:layout_height="220dp" android:fitsSystemWindows="true" > <!--android:theme="#style/AppTheme.AppBarOverlay"--> <android.support.design.widget.CollapsingToolbarLayout android:id="#+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:toolbarId="#+id/toolbar"> <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:scaleType="centerCrop" app:layout_collapseMode="pin" app:srcCompat="#drawable/place_holder" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginLeft="6dp" android:layout_marginStart="6dp" android:layout_marginTop="8dp" android:src="#mipmap/next" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> <android.support.v7.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="#style/AppTheme.PopupOverlay"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <include layout="#layout/content_display_shop" /> </android.support.design.widget.CoordinatorLayout>
you can use supportActionBar and change title with "" (string null) setSupportActionBar(findViewById(R.id.toolbar)) findViewById<CollapsingToolbarLayout>(R.id.toolbar_layout).title = title supportActionBar!!.title="" supportActionBar!!.setDisplayHomeAsUpEnabled(true) or you can change in findViewById findViewById<CollapsingToolbarLayout>(R.id.toolbar_layout).title = title
Calling this method from onCreate() initCollapsingToolbar(); Defining the method private void initCollapsingToolbar() { final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout); collapsingToolbar.setTitle(" "); AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar); appBarLayout.setExpanded(true); // hiding & showing the title when toolbar expanded & collapsed appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { boolean isShow = false; int scrollRange = -1; #Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (scrollRange == -1) { scrollRange = appBarLayout.getTotalScrollRange(); } if (scrollRange + verticalOffset == 0) { collapsingToolbar.setTitle("Your app title"); isShow = true; } else if (isShow) { collapsingToolbar.setTitle(" "); isShow = false; } } }); }
How to center align the ActionBar title in Android?
I am trying to use the following code to center the text in the ActionBar, but it aligns itself to the left. How do you make it appear in the center? ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle("Canteen Home"); actionBar.setHomeButtonEnabled(true); actionBar.setIcon(R.drawable.back);
To have a centered title in ABS (if you want to have this in the default ActionBar, just remove the "support" in the method names), you could just do this: In your Activity, in your onCreate() method: getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.abs_layout); abs_layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical"> <androidx.appcompat.widget.AppCompatTextView android:id="#+id/tvTitle" style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#FFFFFF" /> </LinearLayout> Now you should have an Actionbar with just a title. If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent"). or with: getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));
I haven't had much success with the other answers... below is exactly what worked for me on Android 4.4.3 using the ActionBar in the support library v7. I have it set up to show the navigation drawer icon ("burger menu button") XML <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="#+id/actionbar_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:maxLines="1" android:clickable="false" android:focusable="false" android:longClickable="false" android:textStyle="bold" android:textSize="18sp" android:textColor="#FFFFFF" /> </LinearLayout> Java //Customize the ActionBar final ActionBar abar = getSupportActionBar(); abar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_background));//line under the action bar View viewActionBar = getLayoutInflater().inflate(R.layout.actionbar_titletext_layout, null); ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar ! ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER); TextView textviewTitle = (TextView) viewActionBar.findViewById(R.id.actionbar_textview); textviewTitle.setText("Test"); abar.setCustomView(viewActionBar, params); abar.setDisplayShowCustomEnabled(true); abar.setDisplayShowTitleEnabled(false); abar.setDisplayHomeAsUpEnabled(true); abar.setIcon(R.color.transparent); abar.setHomeButtonEnabled(true);
Define your own custom view with title text, then pass LayoutParams to setCustomView(), as Sergii says. ActionBar actionBar = getSupportActionBar() actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null), new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER ) ); EDITED: At least for width, you should use WRAP_CONTENT or your navigation drawer, app icon, etc. WON'T BE SHOWN (custom view shown on top of other views on action bar). This will occur especially when no action button is shown. EDITED: Equivalent in xml layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_horizontal" android:orientation="vertical"> This doesn't require LayoutParams to be specified. actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null);
Just a quick addition to Ahmad's answer. You can't use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view: TextView textViewTitle = (TextView) findViewById(R.id.mytext); textViewTitle.setText(R.string.title_for_this_activity);
Code here working for me. // Activity public void setTitle(String title){ getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView textView = new TextView(this); textView.setText(title); textView.setTextSize(20); textView.setTypeface(null, Typeface.BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); textView.setGravity(Gravity.CENTER); textView.setTextColor(getResources().getColor(R.color.white)); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(textView); } // Fragment public void setTitle(String title){ ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true); ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView textView = new TextView(getActivity()); textView.setText(title); textView.setTextSize(20); textView.setTypeface(null, Typeface.BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); textView.setGravity(Gravity.CENTER); textView.setTextColor(getResources().getColor(R.color.white)); ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView); }
Without customview its able to center actionbar title. It's perfectly working for navigation drawer as well int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); TextView abTitle = (TextView) findViewById(titleId); abTitle.setTextColor(getResources().getColor(R.color.white)); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); abTitle.setGravity(Gravity.CENTER); abTitle.setWidth(metrics.widthPixels); getActionBar().setTitle("I am center now");
OK. After a lot of research, combined with the accepted answer above, I have come up with a solution that also works if you have other stuff in your action bar (back/home button, menu button). So basically I have put the override methods in a basic activity (which all other activities extend), and placed the code there. This code sets the title of each activity as it is provided in AndroidManifest.xml, and also does som other custom stuff (like setting a custom tint on action bar buttons, and custom font on the title). You only need to leave out the gravity in action_bar.xml, and use padding instead. actionBar != null check is used, since not all my activities have one. Tested on 4.4.2 and 5.0.1 public class BaseActivity extends AppCompatActivity { private ActionBar actionBar; private TextView actionBarTitle; private Toolbar toolbar; #Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); super.onCreate(savedInstanceState); ... getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setElevation(0); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(R.layout.action_bar); LinearLayout layout = (LinearLayout) actionBar.getCustomView(); actionBarTitle = (TextView) layout.getChildAt(0); actionBarTitle.setText(this.getTitle()); actionBarTitle.setTypeface(Utility.getSecondaryFont(this)); toolbar = (Toolbar) layout.getParent(); toolbar.setContentInsetsAbsolute(0, 0); if (this.getClass() == BackButtonActivity.class || this.getClass() == AnotherBackButtonActivity.class) { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable wrapDrawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_back)); DrawableCompat.setTint(wrapDrawable, getResources().getColor(android.R.color.white)); actionBar.setHomeAsUpIndicator(wrapDrawable); actionBar.setIcon(null); } else { actionBar.setHomeButtonEnabled(false); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setDisplayShowHomeEnabled(false); actionBar.setHomeAsUpIndicator(null); actionBar.setIcon(null); } } try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // Ignore } } #Override public boolean onCreateOptionsMenu(Menu menu) { if (actionBar != null) { int padding = (getDisplayWidth() - actionBarTitle.getWidth())/2; MenuInflater inflater = getMenuInflater(); if (this.getClass() == MenuActivity.class) { inflater.inflate(R.menu.activity_close_menu, menu); } else { inflater.inflate(R.menu.activity_open_menu, menu); } MenuItem item = menu.findItem(R.id.main_menu); Drawable icon = item.getIcon(); icon.mutate().mutate().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_IN); item.setIcon(icon); ImageButton imageButton; for (int i =0; i < toolbar.getChildCount(); i++) { if (toolbar.getChildAt(i).getClass() == ImageButton.class) { imageButton = (ImageButton) toolbar.getChildAt(i); padding -= imageButton.getWidth(); break; } } actionBarTitle.setPadding(padding, 0, 0, 0); } return super.onCreateOptionsMenu(menu); } ... And my action_bar.xml is like this (if anyone is interested): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#color/actionbar_text_color" android:textAllCaps="true" android:textSize="9pt" /> </LinearLayout> EDIT: If you need to change the title to something else AFTER the activity is loaded (onCreateOptionsMenu has already been called), put another TextView in your action_bar.xml and use the following code to "pad" this new TextView, set text and show it: protected void setSubTitle(CharSequence title) { if (!initActionBarTitle()) return; if (actionBarSubTitle != null) { if (title != null || title.length() > 0) { actionBarSubTitle.setText(title); setActionBarSubTitlePadding(); } } } private void setActionBarSubTitlePadding() { if (actionBarSubTitlePaddingSet) return; ViewTreeObserver vto = layout.getViewTreeObserver(); if(vto.isAlive()){ vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { #Override public void onGlobalLayout() { int padding = (getDisplayWidth() - actionBarSubTitle.getWidth())/2; ImageButton imageButton; for (int i = 0; i < toolbar.getChildCount(); i++) { if (toolbar.getChildAt(i).getClass() == ImageButton.class) { imageButton = (ImageButton) toolbar.getChildAt(i); padding -= imageButton.getWidth(); break; } } actionBarSubTitle.setPadding(padding, 0, 0, 0); actionBarSubTitlePaddingSet = true; ViewTreeObserver obs = layout.getViewTreeObserver(); obs.removeOnGlobalLayoutListener(this); } }); } } protected void hideActionBarTitle() { if (!initActionBarTitle()) return; actionBarTitle.setVisibility(View.GONE); if (actionBarSubTitle != null) { actionBarSubTitle.setVisibility(View.VISIBLE); } } protected void showActionBarTitle() { if (!initActionBarTitle()) return; actionBarTitle.setVisibility(View.VISIBLE); if (actionBarSubTitle != null) { actionBarSubTitle.setVisibility(View.GONE); } } EDIT (25.08.2016): This does not work with appcompat 24.2.0 revision (August 2016), if your activity has a "back button". I filed a bug report (Issue 220899), but I do not know if it is of any use (doubt it will be fixed any time soon). Meanwhile the solution is to check if the child's class is equal to AppCompatImageButton.class and do the same, only increase the width by 30% (e.g. appCompatImageButton.getWidth()*1.3 before subtracting this value from the original padding): padding -= appCompatImageButton.getWidth()*1.3; In the mean time I threw in some padding/margin checks in there: Class<?> c; ImageButton imageButton; AppCompatImageButton appCompatImageButton; for (int i = 0; i < toolbar.getChildCount(); i++) { c = toolbar.getChildAt(i).getClass(); if (c == AppCompatImageButton.class) { appCompatImageButton = (AppCompatImageButton) toolbar.getChildAt(i); padding -= appCompatImageButton.getWidth()*1.3; padding -= appCompatImageButton.getPaddingLeft(); padding -= appCompatImageButton.getPaddingRight(); if (appCompatImageButton.getLayoutParams().getClass() == LinearLayout.LayoutParams.class) { padding -= ((LinearLayout.LayoutParams) appCompatImageButton.getLayoutParams()).getMarginEnd(); padding -= ((LinearLayout.LayoutParams) appCompatImageButton.getLayoutParams()).getMarginStart(); } break; } else if (c == ImageButton.class) { imageButton = (ImageButton) toolbar.getChildAt(i); padding -= imageButton.getWidth(); padding -= imageButton.getPaddingLeft(); padding -= imageButton.getPaddingRight(); if (imageButton.getLayoutParams().getClass() == LinearLayout.LayoutParams.class) { padding -= ((LinearLayout.LayoutParams) imageButton.getLayoutParams()).getMarginEnd(); padding -= ((LinearLayout.LayoutParams) imageButton.getLayoutParams()).getMarginStart(); } break; } }
It works nicely. activity = (AppCompatActivity) getActivity(); activity.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.custom_actionbar, null); ActionBar.LayoutParams p = new ActionBar.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); ((TextView) v.findViewById(R.id.title)).setText(FRAGMENT_TITLE); activity.getSupportActionBar().setCustomView(v, p); activity.getSupportActionBar().setDisplayShowTitleEnabled(true); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); Below layout of custom_actionbar: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="#+id/title" android:layout_width="wrap_content" android:text="Example" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ellipsize="end" android:maxLines="1" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#color/colorBlack" /> </RelativeLayout>
Best and easiest way, specifically for those who just want text view with gravity center without any xml layout. AppCompatTextView mTitleTextView = new AppCompatTextView(getApplicationContext()); mTitleTextView.setSingleLine(); ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; actionBar.setCustomView(mTitleTextView, layoutParams); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP); mTitleTextView.setText(text); mTitleTextView.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);
A Kotlin-only solution that does not require to have changes in the XML Layouts: //Function to call in onResume() of your activity private fun centerToolbarText() { val mTitleTextView = AppCompatTextView(this) mTitleTextView.text = title mTitleTextView.setSingleLine()//Remove it if you want to allow multiple lines in the toolbar mTitleTextView.textSize = 25f val layoutParams = android.support.v7.app.ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT ) layoutParams.gravity = Gravity.CENTER supportActionBar?.setCustomView(mTitleTextView,layoutParams) supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM }
After a lot of research: This actually works: getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getActionBar().setCustomView(R.layout.custom_actionbar); ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); p.gravity = Gravity.CENTER; You have to define custom_actionbar.xml layout which is as per your requirement e.g. : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:background="#2e2e2e" android:orientation="vertical" android:gravity="center" android:layout_gravity="center"> <ImageView android:id="#+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="#drawable/top_banner" android:layout_gravity="center" /> </LinearLayout>
You need to set ActionBar.LayoutParams.WRAP_CONTENT and ActionBar.DISPLAY_HOME_AS_UP View customView = LayoutInflater.from(this).inflate(R.layout.actionbar_title, null); ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP );
Here is a complete Kotlin + androidx solution, building upon the answer from #Stanislas Heili. I hope it may be useful to others. It's for the case when you have an activity that hosts multiple fragments, with only one fragment active at the same time. In your activity: private lateinit var customTitle: AppCompatTextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // stuff here customTitle = createCustomTitleTextView() // other stuff here } private fun createCustomTitleTextView(): AppCompatTextView { val mTitleTextView = AppCompatTextView(this) TextViewCompat.setTextAppearance(mTitleTextView, R.style.your_style_or_null); val layoutParams = ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT ) layoutParams.gravity = Gravity.CENTER supportActionBar?.setCustomView(mTitleTextView, layoutParams) supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM return mTitleTextView } override fun setTitle(title: CharSequence?) { customTitle.text = title } override fun setTitle(titleId: Int) { customTitle.text = getString(titleId) } In your fragments: override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.title = "some title for fragment" }
The other tutorials I've seen override the whole action bar layout hiding the MenuItems. I've got it worked just doing the following steps: Create a xml file as following: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="#+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ellipsize="end" android:maxLines="1" android:text="#string/app_name" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#android:color/white" /> </RelativeLayout> And in the classe do it: LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflator.inflate(R.layout.action_bar_title, null); ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER); TextView titleTV = (TextView) v.findViewById(R.id.title); titleTV.setText("Test");
For Kotlin users: Use the following code in your activity: // Set custom action bar supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM supportActionBar?.setCustomView(R.layout.action_bar) // Set title for action bar val title = findViewById<TextView>(R.id.titleTextView) title.setText(resources.getText(R.string.app_name)) And the XML/ resource layout: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="#+id/titleTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Title" android:textColor="#color/black" android:textSize="18sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
My solution will be to keep text part of tool bar separate, to define style and say, center or whichever alignment. It can be done in XML itself. Some paddings can be specified after doing calculations when you have actions that are visible always. I have moved two attributes from toolbar to its child TextView. This textView can be provided id to be accessed from fragments. <?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="#style/AppTheme.AppBarOverlay"> <androidx.appcompat.widget.Toolbar android:id="#+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" > <!--android:theme="#style/defaultTitleTheme" app:titleTextColor="#color/white"--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingStart="#dimen/icon_size" android:text="#string/title_home" style="#style/defaultTitleTheme" tools:ignore="RtlSymmetry" /> </androidx.appcompat.widget.Toolbar> </com.google.android.material.appbar.AppBarLayout> <FrameLayout android:id="#+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
Here's a quick tip to center align the action: android:label=" YourTitle" Assuming that you have Actionbar Enable, You can add this in your activity with some space (Can be adjusted) to place the title at the center. However, This is just diddly and unreliable method. You probably shouldn't do that. So, The best thing to do is to create a custom ActionBar. So, What you wanna do is remove the default Actionbar and use this to replace it as an ActionBar. <androidx.constraintlayout.widget.ConstraintLayout android:elevation="30dp" android:id="#+id/customAction" android:layout_width="match_parent" android:layout_height="56dp" android:background="#color/colorOnMain" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="#string/app_name" android:textAllCaps="true" android:textColor="#FFF" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> I have used Constraint Layout to center the textView and used 10dp elevation with 56dp height so that it looks as same as the default ActionBar.
This code will not hide back button, Same time will align the title in centre. call this method in oncreate centerActionBarTitle(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT)); private void centerActionBarTitle() { int titleId = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { titleId = getResources().getIdentifier("action_bar_title", "id", "android"); } else { // This is the id is from your app's generated R class when // ActionBarActivity is used for SupportActionBar titleId = R.id.action_bar_title; } // Final check for non-zero invalid id if (titleId > 0) { TextView titleTextView = (TextView) findViewById(titleId); DisplayMetrics metrics = getResources().getDisplayMetrics(); // Fetch layout parameters of titleTextView // (LinearLayout.LayoutParams : Info from HierarchyViewer) LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams(); txvPars.gravity = Gravity.CENTER_HORIZONTAL; txvPars.width = metrics.widthPixels; titleTextView.setLayoutParams(txvPars); titleTextView.setGravity(Gravity.CENTER); } }