How to center the alignment of an ActionBar header in Android?

I am trying to use the following code to center text in an ActionBar , but it is aligned to the left.

How do you show it in the center?

 ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle("Canteen Home"); actionBar.setHomeButtonEnabled(true); actionBar.setIcon(R.drawable.back); 
+89
android android-actionbar android-theme
Sep 12
source share
14 answers

To have a centered title in the ABS (if you want to have this in the ActionBar by default, just remove the “support” in the method names), you can simply do this:

In your activity, in your onCreate() :

 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"> <android.support.v7.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> 

You should now have an Actionbar with a title. If you want to set a custom background, set it in the layout above (but then remember to set android:layout_height="match_parent" ).

or with:

 getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage)); 
+188
Sep 12 '12 at 12:29
source share

I did not have much success with the other answers ... below is exactly what worked for me on Android 4.4.3 using ActionBar in the v7 support library. I configured it to display the navigation box icon ("hamburger 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); 
+34
Jun 11 '14 at 21:33
source share

Define your own custom view with title text, then pass LayoutParams to setCustomView (), as Sergius 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 box, application icon, etc. WILL NOT SHOW (custom view is shown on top of other views in the action bar). This will happen, especially when the action button is not displayed.

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 does not require specifying LayoutParams.

 actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null); 
+9
May 15 '14 at 5:14
source share

Just a quick complement to Ahmad’s answer. You cannot use getSupportActionBar (). SetTitle is more when using custom view with TextView. So, to set the title when you have several operations 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); 
+8
Dec 01 '13 at 11:21
source share

OK After a lot of research, combined with the accepted answer above, I came up with a solution that also works if you have other things in the action bar (back / home button, menu button). So basically I put the override methods in the main action (which applies to all other actions) and put the code there. This code sets the title for each activity, as presented in AndroidManifest.xml, and also makes some other custom elements (for example, customize the hue on the buttons on the action bar and its own font in the title). You only need to leave gravity in the action_bar.xml file and use a pad instead. actionBar != null used since not all my actions 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 looks 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 loading the activity (onCreateOptionsMenu has already been called), add another TextView to your action_bar.xml file and use the following code to “pad” this new TextView, set the 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 (08/25/2016) . This does not work with appcompat version 24.2.0 (August 2016) if there is a back button in your activity. I published a bug report ( Issue 220899 ), but I don’t know if it will be used (doubt that it will be fixed soon). Meanwhile, the solution is to check if the child class is equal to the AppCompatImageButton class. class and do the same, only increase the width by 30% (for example, appCompatImageButton.getWidth () * 1.3, before subtracting this value from the original addition):

 padding -= appCompatImageButton.getWidth()*1.3; 

At the same time, I threw some fill / field checks:

  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; } } 
+4
Feb 25 '16 at 16:05
source share

without a special view that can center the title of the action bar. it works fine for the navigation box

  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"); 

Happy coding. thank.

+4
Nov 03 '16 at 7:06
source share

After a lot of research: This really 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 need to define a custom_actionbar.xml layout that matches your requirement, for example.

 <?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> 
+3
Oct 05 '15 at 6:34
source share

It works well.

 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 is the location 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> 
+3
Feb 09 '16 at 19:50
source share

The best and easiest way, especially for those who just want to see text with a center of gravity 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); 
+2
Jul 04 '18 at 11:16
source share

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 ); 
+1
Aug 17 '14 at 1:11
source share

The code here works 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); } 
+1
May 16 '19 at 4:55
source share

Other tutorials I've seen redefine the entire action bar structure that hides MenuItems. I worked by following these steps:

Create the xml file as follows:

 <?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 this case do this:

 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"); 
0
Jan 20 '14 at 18:08
source share

This code will not hide the back button, at the same time the title will be aligned in the center.

calling 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 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); } } 
0
Feb 22 '16 at 12:42 on
source share

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> 
0
Jun 28 '18 at 4:11
source share



All Articles