Ponting Ponting - 1 year ago 91
Android Question

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

I searched a lot but can not find a way, How can I set then title at center of ActionBar instead of left aligned. I used below code to set the title at center :

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

But it gives error as below :

ClassCastException : com.android.internal.widget.ActionBarView can not
be cast to android.widget.TextView.

Any other solution ..Any help will be appreciated.

Answer Source

You can create a custom layout and apply it to the actionBar.

To do so, follow those 2 simple steps:

  1. Java Code

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar);

Where R.layout.actionbar is the following layout.

  1. XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:text="YOUR ACTIVITY TITLE"
        android:textSize="24sp" />

It can be as complex as you want. Try it out!


To set the background you can use the property android:background in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height to match_parent instead of wrap_content.

Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation to horizontal (or simply use a RelativeLayout and manage it by yourself).

To change the title of above custom action bar dynamically, do this:

TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");