Android – Handling ActionBar title with the fragment back stack

actionbarsherlockandroidandroid-actionbarandroid-fragments

I have an Activity where I load in a ListFragment and, upon clicking, it drills down a level and a new type of ListFragment is shown, replacing the original one (using the showFragment method below). This is placed on the back stack.

At the beginning, the activity shows the default title in the action bar (i.e. it's set automatically based on the application's android:label).

When showing the list for the next level in the hierarchy, the name of the item clicked on should become the action bar's title.

However, when pressing Back, I would like the original default title to be restored. This isn't something FragmentTransaction knows about, so the title isn't restored.

I've vaguely read about FragmentBreadCrumbs, but this seems to require using a custom view. I'm using ActionBarSherlock and would prefer to not have my own custom title view.

What is the best way of doing this? Is it possible without a load of boilerplate code and having to keep track of the titles shown along the way?


protected void showFragment(Fragment f) {
  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  ft.replace(R.id.fragment_container, f);
  ft.addToBackStack(null);
  ft.commit();
}

Best Answer

In every fragment and every activity I change the title like this. This way the active title will always be correct:

@Override
public void onResume() {
    super.onResume();
    // Set title
    getActivity().getActionBar()
        .setTitle(R.string.thetitle);
}

There is some cases where onResume isn't called inside fragments. In some of these cases we can use:

public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser) {
        // Set title
        getActivity().getActionBar()
            .setTitle(R.string.thetitle);
    }
}