Dec 06

If you’ve been dealing with Android fragments, odds are you’ve used the FragmentTransaction.addToBackStack() method. Often this method is called with a null argument, and that’s fine for most uses. Afterwards, you can pop the top of the back stack by calling FragmentManager.popBackStack() and you’re done.

You might be wondering what use is the String parameter in the addToBackStack() method. It can be quite useful in cases where you need to pop a number of items from the FragmentManager back stack at once. For example, you may want to wipe the slate clean of all fragments that you’ve been adding/replacing. You can do this as follows:

    FragmentManager fragMan = getFragmentManager();
    for (int i = 0; i < fragMan.getBackStackEntryCount(); ++i) {
        fragMan.popBackStack();
    }

Now, in case you want to leave one or more items on the back stack instead of popping the whole lot, you could try to keep track of the number of back stack items to pop, but this is tedious and error-prone to say the least. Here’s where addToBackStack()’s String argument comes to play. The String argument is the name of a back stack “state” you want to keep track of.

Let’s say that you have a two-pane layout, and on the right side you have a fragment that you’ve replace()d to a layout element. You’d like to keep this fragment visible at all times. You then proceed to utilize other fragments as well in the same layout spot, calling FragmentTransaction.replace() in the process, along with addToBackStack(). If you then want to pop all other back stack items but the first one, you can do this by adding a predefined state name to the first fragment’s addToBackStack() method:

    private static final String INITIAL_FRAGMENT_STATE = "initial_fragment_state";
    // ...
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(...);
    ft.addToBackStack(INITIAL_FRAGMENT_STATE);

Then, when you need to wipe the slate clean and lose all but the initial state from the back stack:

    getFragmentManager().popBackStack(INITIAL_FRAGMENT_STATE);

And there you have it. No need to keep track of the number of fragments in the back stack in each valid state of the application or any such nonsense. Just make use of named back stack states.

preload preload preload