75

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

11 Answers 11

124

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);
    }
}
25
  • 2
    I had no need to cast, or get the action bar (i.e. I just call getActivity().setTitle(...)), but this is a reasonable approach. Thanks. Nov 23, 2012 at 19:37
  • 9
    -1. This approach is incorrect! According to Android Design guidelines, when switching fragments using Navigation Drawer, the Action Bar title should only change in the Navigation Drawer onClosed callback. Your approach will incorrectly change the title before the Navigation Drawer is closed.
    – zyamys
    Feb 20, 2014 at 21:57
  • 6
    @zyamys If you come with a better suggestion I'd gladly upvote it. This was the best answer I could come up with at the time.
    – Warpzit
    Feb 21, 2014 at 7:48
  • 7
    This didn't work for me so I changed it to getActivity().setTitle(R.string.thetitle); and then it worked.
    – simeg
    Mar 8, 2015 at 18:22
  • 4
    this works only if you replace the fragment during FragmentTransaction. what if you add a fragment instead of replace ?
    – Kamlesh
    Mar 7, 2016 at 8:49
29

As the original answer is quite old, this might come of help as well. As the documentation states, one might want to register a listener to listen on the back stack changes in the hosting Activity:

getSupportFragmentManager().addOnBackStackChangedListener(
        new FragmentManager.OnBackStackChangedListener() {
            public void onBackStackChanged() {
                // Update your UI here.
            }
        });

Then, identify the situation in the callback method and set a proper title, without accessing the ActionBar from the Fragment.

This is a more elegant solution as the Fragment doesn't have to know about the ActionBar existence and Activity is usually the place that is managing the backstack so having it handled over there seems to be more appropriate. Fragment should at all time be considered only by its own content, not the surroundings.

More on the topic in the documentation.

7
  • 1
    The other answer is old, but I still find it the simplest and most pragmatic way of ensuring the title is always correct. As mentioned in my comment, you do not need to access the ActionBar directly. The solution here requires more code, but also doesn't help for your initial fragment, which normally does not get added to the back stack. Apr 23, 2014 at 17:58
  • 1
    Also there is nothing wrong with accessing the actionbar from fragments. Google also provides api for changing menu items inside fragments.
    – Warpzit
    Apr 24, 2014 at 7:20
  • 2
    After some time I came to a conclusion that both solutions are fine, it just depends on your use case, sometimes it will be more feasible to use onResume and sometimes a fragment manager listener. So all in all it is good to know your tools, so you can apply them adequately to your needs. Jul 2, 2014 at 15:25
  • 2
    @Maciej Pigulski And then? We do not know anything about the context in this callback.
    – fralbo
    Jun 7, 2015 at 16:17
  • 2
    @caBBAlainB, context is being held in the hosting Activity's FragmentManager so you would have to determine the title doing some cumbersome checks on the manager - thus it is not great. Today I can't remember what was my reasoning here. I think this idea mostly comes from what is written in Android docs linked in this answer (paragraph above the listener snippet). Today I would rather go and use the accepted answer. Jun 8, 2015 at 9:37
11

Let the controlling activity do all the work as follows:

Listen for backstack events (in onCreate() of activity):

// Change the title back when the fragment is changed
    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            Fragment fragment = getFragment();
            setTitleFromFragment(fragment);
        }
    });

Get the current fragment from the container:

/**
 * Returns the currently displayed fragment.
 * @return
 *      Fragment or null.
 */
private Fragment getFragment() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
    return fragment;
}

Set the fragment inside the content view:

private void setFragment(Fragment fragment, boolean addToBackStack) {
    // Set the activity title
    setTitleFromFragment(fragment);
    .
    .
    .
}
5
  • This is not "letting the activity do all the work" if you have implement some interface in every single Fragment so that setTitleFromFragment() can retrieve its title. None of which seems to fit the "without a load of boilerplate code" part of my question. Oct 9, 2014 at 20:36
  • There is no mention of an interface in my solution, your activity can check the instance of the fragment and set the title based on that, thus letting your activity do all the work. All those methods are defined inside the activity.
    – Meanman
    Oct 10, 2014 at 8:36
  • Yeah, that sounds probably even worse from a design/separation of concerns/reusability point of view. Plus this redundantly changes the title twice for each fragment added to the backstack, since setTitleFromFragment method is called unconditionally in setFragment, I guess? Anyway, thanks, but I'll stick with the pragmatic and simple accepted answer :) Oct 10, 2014 at 9:31
  • 3
    How does this sound "probably even worse from a design/separation of concerns/reusability point of view"? Please back it up with a valid argument? You're letting the activity be a "controller" and set its own title based on its content. What if I want to use a fragment in multiple places, or have an activity with multiple fragments, and they all try to set the title.
    – Meanman
    Oct 13, 2014 at 10:45
  • Much helpful answer
    – VVB
    Jan 25, 2017 at 6:56
7

Warpzit is right. This also solves title problem when orientation of device is changed. Also if you use support v7 for action bar, you can get action bar from fragment like this :

@Override
public void onResume() {
    super.onResume();
    ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle("Home");
}
2
  • +1 for support v7. I think whenever an android answer is given the person answering should take support into account. As of now, to reach 80% device coverage, you HAVE to go back to API 16. In most cases that requires using the compat libraries.
    – akousmata
    Jun 23, 2015 at 16:21
  • 1
    i put your code in public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) method and worked fine.
    – GFPF
    Nov 26, 2015 at 0:01
7

It is best to let the OS do as much of the work as possible. Assuming each fragment is properly named using .addToBackStack("title") then you can override onBackPressed something like this to achieve desired behavior:

// this example uses the AppCompat support library
// and works for dynamic fragment titles
@Override
public void onBackPressed() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    int count = fragmentManager.getBackStackEntryCount();
    if (count <= 1) {
        finish();
    }
    else {
        String title = fragmentManager.getBackStackEntryAt(count-2).getName();
        if (count == 2) {
            // here I am using a NavigationDrawer and open it when transitioning to the initial fragment
            // a second back-press will result in finish() being called above.
            mDrawerLayout.openDrawer(mNavigationDrawerFragment.getView());
        }
        super.onBackPressed();
        Log.v(TAG, "onBackPressed - title="+title);
        getSupportActionBar().setTitle(title);
    }
}
0
5

I use a similar solution to Lee approach, but replacing onBackStackChanged() method instead.

First I set the fragment name when adding the transaction to the back stack.

getSupportFragmentManager().beginTransaction()
                .replace(R.id.frame_content, fragment)
                .addToBackStack(fragmentTitle)
                .commit();

Then I override the onBackStackChanged() method and I call setTitle() with the last backstack entry name.

@Override
public void onBackStackChanged() {
    int lastBackStackEntryCount = getSupportFragmentManager().getBackStackEntryCount() - 1;
    FragmentManager.BackStackEntry lastBackStackEntry =
            getSupportFragmentManager().getBackStackEntryAt(lastBackStackEntryCount);

    setTitle(lastBackStackEntry.getName());
}
1
  • 3
    The problem with using the backstack entry name is that it doesn't handle configuration changes. An interesting and proper way to handle this issue would be to use setBreadCrumbTitle(int res) to save a title resource id, which you could use in the onBackStackChanged to set the title.
    – David Liu
    Nov 3, 2016 at 19:30
4

Use Fragments method:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)

It is called on every Fragment appearance, but onResume is not.

2
  • yes.. none of the answer are not saved my problem.. this works fine. It may not professional way.. but it little bit hacky. Apr 30, 2016 at 14:28
  • @Bevor for this to work you need an options menu, you can activate it for a fragment by calling "setHasOptionsMenu(true);" in the OnCreateView(...) method of your fragment.
    – Dwagner
    Mar 20, 2019 at 18:32
1

The best approach is to make use of the android provided Interface OnBackStackChangedListener method onBackStackChanged().

Lets say we have a navigation drawer with 4 options to which the user can navigate to. In that case we will have 4 fragments. Lets see the code first and then I will explain the working.

    private int mPreviousBackStackCount = 0;
    private String[] title_name = {"Frag1","Frag2","Frag3","Frag4"};
    Stack<String> mFragPositionTitleDisplayed;

    public class MainActivity extends ActionBarActivity implements FragmentManager.OnBackStackChangedListener
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ....
    ....
    ....
    getSupportFragmentManager().addOnBackStackChangedListener(this);
    mFragPositionTitleDisplayed = new Stack<>();
}

public void displayFragment() {
    Fragment fragment = null;
    String title = getResources().getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new Fragment1();
            title = title_name[position];
            break;
        case 1:
            fragment = new Fragment2();
            title = title_name[position];
            break;
        case 2:
            fragment = new Fragment3();
            title = title_name[position];
            break;
        case 3:
            fragment = new Fragment4();
            title = title_name[position];
            break;
        default:
            break;
    }
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container_body, fragment)
                .addToBackStack(null)
                .commit();
        getSupportActionBar().setTitle(title);
    }
}

@Override
public void onBackStackChanged() {
    int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
    if(mPreviousBackStackCount >= backStackEntryCount) {
        mFragPositionTitleDisplayed.pop();
        if (backStackEntryCount == 0)
            getSupportActionBar().setTitle(R.string.app_name);
        else if (backStackEntryCount > 0) {
            getSupportActionBar().setTitle(mFragPositionTitleDisplayed.peek());
        }
        mPreviousBackStackCount--;
    }
    else{
        mFragPositionTitleDisplayed.push(title_name[position]);
        mPreviousBackStackCount++;
    }

}   

In the code shown we have the displayFragment() method. Here I display the fragment on the basis of option chosen from the navigation drawer.The variable position corresponds to the position of the item clicked from the ListView or RecyclerView in the navigation drawer. I set the actionbar title accordingly with getSupportActionBar.setTitle(title), where the title stores the appropriate title name.

Whenever we click the item from nav drawer a fragment is displayed depending on the item clicked to the user. But on the back end side this fragment is added to the backstack and the method onBackStachChanged(), gets hit. What I have done is that I have created a variable mPreviousBackStackCount and initialized it to 0. I have also created an additional stack which will store the action bar title names. Whenever I add a new fragment to the backstack, I add the corresponding title name to my created stack. On the opposite side whenever I press the back button onBackStackChanged() is called and I pop the last title name from my stack and set the title to the name derived by the peek() method of the stack.

Example:

Lets say our android backstack is empty:

Press Choice 1 from nav drawer: onBackStachChanged() is called and the Fragment 1 is added to android backstack, backStackEntryCount is set to 1 and Frag1 is pushed to my stack and size of mFragPositionTitleDisplayed becomes 1.

Press Choice 2 from nav drawer: onBackStachChanged() is called and the Fragment 2 is added to android backstack, backStackEntryCount is set to 2 and Frag2 is pushed to my stack and size of mFragPositionTitleDisplayed becomes 2.

Now we have 2 elements both in the android stack and my stack. When you press back button onBackStackChanged() is called and the value of backStackEntryCount is 1. The code enters the if part and pops out the last entry from my stack. So, the android backstack has only 1 fragment - "Fragment 1" and my stack has only 1 title - "Frag1". Now I just peek() the title from my stack and set the action bar to that title.

Remember: To set the action bat title use peek() and not pop() else your application will crash when you open more than 2 fragments and try to go back by pressing back button.

2
  • This is a ridiculous amount of code (especially compared to the accepted answer), and ignores my requirements in the question, i.e. to implement this without a load of boilerplate code and without having to keep track of the titles shown. Jul 4, 2015 at 23:18
  • Yeah, well its your problem if you dont want excessive code. You got to compromise somewhere. Moreover the only important part in the code is OnBackStackChanged().
    – Abhishek
    Jul 5, 2015 at 16:49
1

You can Solve with onKeyDown! I have a bool mainisopen=true <-- MainFragment is Visible other Fragment mainisopen=false

and here is My Code:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && mainisopen == false) {
        mainisopen = true;
        HomeFrag fragment = new HomeFrag();
        FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragmet_cont, fragment);
        fragmentTransaction.commit();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
        navigationView.setNavigationItemSelectedListener(this);
        this.setTitle("Digi - Home"); //Here set the Title back
        return true;
    } else {
        if (keyCode == KeyEvent.KEYCODE_BACK && mainisopen == true) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Wollen sie die App schliessen!");
            builder.setCancelable(true);

            builder.setPositiveButton("Ja!", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(1);
                }
            });

            builder.setNegativeButton("Nein!", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(getApplicationContext(), "Applikation wird fortgesetzt", Toast.LENGTH_SHORT).show();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
0

As described here my solution is adding this code to MainActivity onCreate method(): and changing actionbar title

FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
    @Override
    public void onBackStackChanged() {
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.My_Container_1_ID);
        currentFragment.onResume();
    }
});

and changing actionbar title in fragment's onResume() method

@Override
public void onResume() {
    super.onResume();
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    ActionBar actionBar = activity.getSupportActionBar();
    if(actionBar!=null) {
        actionBar.setTitle("Fragment Title");
        actionBar.setSubtitle("Subtitle");
    }

}
-4

To update the actionbar title on back press. Just simply put

getActivity.setTitle("title")

inside onCreateView method.

1
  • 2
    onCreateView is only called when ... creating a view. If you press Back and the previous activity/fragment is still on the stack, then this method will not be called. May 28, 2015 at 13:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.