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


View title =(View)getWindow().findViewById(;
FrameLayout titlebar=(FrameLayout)title.getParent();
TextView txt = (TextView)titlebar.getChildAt(0);

add this code in onCreate() of your activity.


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

  1. I am getting “java.lang.ClassCastException: 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.

      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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s