Alligning the title bar’s text in android

By default your title bar text remains left aligned , to change this get the TextView of the title which is originally loaded while onCreate() is executed and override that. By changing the gravity of that text view you can align your title. In the same way the background of the title bar can be changed by getting its parent layout and changing its background property.

ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView(); 
LinearLayout root= (LinearLayout) decorView.getChildAt(0); 
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0); 
TextView title= (TextView) titleContainer.getChildAt(0); 
title.setGravity(Gravity.CENTER);

OR

View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
titlebar.setBackgroundColor(Color.TRANSPARENT);
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);

add this code in onCreate() of your activity.

Advertisements

4 thoughts on “Alligning the title bar’s text in android

  1. I am getting “java.lang.ClassCastException: com.android.internal.widget.ActionBarView cannot be cast to android.widget.TextView” Error for same code..Could you please provide any solution.

  2. If you are working on devices greater than 4.0 os this peace of code wont work. As you see, this error is due to ActionBar view. Just to make this code work delete values-v14 and values-v11 folders from your res folder and run your app.

    • I followed this approach but still not working, I am using Android 4.2.
      I tried with following code. Here I used custom layout “my_titlebar_center” with textview aliged center.
      getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
      getActionBar().setCustomView(R.layout.my_titlebar_center);

      This works but for each activity I want different title which is not possible with this approach. Please let me know if you have any idea.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s