Setting Action Bar title and subtitle

Adil Malik picture Adil Malik · Jan 12, 2013 · Viewed 119k times · Source

I want to set title and subtitile of my action bar before compile time. I got a way to do it like this:

ActionBar ab = getActionBar();
ab.setTitle("My Title");
ab.setSubtitle("sub-title");

But I don't want to do it on run time. Is there any xml file or any location where I can specify these titles?

I am trying to achieve this:

enter image description here

Edit:

The reason why I want it in xml is that I want my app to be supported in API level 8. And the method getActionBar() is supported at least on level 11.

Answer

A--C picture A--C · Jan 12, 2013

You can do something like this to code for both versions:

/**
 * Sets the Action Bar for new Android versions.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void actionBarSetup() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    ActionBar ab = getActionBar();
    ab.setTitle("My Title");
    ab.setSubtitle("sub-title"); 
  }
}

Then call actionBarSetup() in onCreate(). The if runs the code only on new Android versions and the @TargetApi allows the code to compile. Therefore it makes it safe for both old and new API versions.

Alternatively, you can also use ActionBarSherlock (see edit) so you can have the ActionBar on all versions. You will have to do some changes such as making your Activities extend SherlockActivity and calling getSupportActionBar(), however, it is a very good global solution.

Edit

Note that when this answer was originally written, ActionBarSherlock, which has since been deprecated, was the go-to compatibility solution.

Nowadays, Google's appcompat-v7 library provides the same functionality but is supported (and actively updated) by Google. Activities wanting to implement an ActionBar must:

  • extend AppCompatActivity
  • use a Theme.AppCompat derivative

To get an ActionBar instance using this library, the aptly-named getSupportActionBar() method is used.