androidandroid-actionbartitlecenter-align

Center Align title in action bar using styles in android.


Hi I am developing android application. In my application I am using action bar. I want to make center align my title of window in action-bar. I know it is possible using xml files. but I want to do it using style so that it will applicable for my every window, how to do this need help. Thank you.


Solution

  • I know it is possible using xml files. but I want to do it using style so that it will applicable for my every window, how to do this need help.

    You still use xml to do this. Just apply the style application wide and not just to a single activity. Please see the android documentation for a complete description:

    https://developer.android.com/training/basics/actionbar/styling.html

    Then apply your theme to your entire app or individual activities:

    <application android:theme="@style/CustomActionBarTheme" ... />
    

    EDIT: Here's how you'll have to handle the centering of the the title:

    In your action_bar.xml you'll have something like this:

    <?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="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="SOME TITLE"
        android:textSize="18sp" />
    </RelativeLayout>
    

    Then in your onCreate() you'll have something like:

    getSupportActionBar().setCustomView(R.layout.action_bar);
    

    If you need to have this in every activity, you have 2 choices:

    1. The brute force way: Put the above line of code in every Activity's onCreate.
    2. Extend Activity and put your ActionBar initialization code in the onCreate. Then Extend your custom Activity class for each Activity. Just don't forget to call the super() in each Activity's onCreate().