Android FragmentTransaction.addToBackStack confusion

Khawar Raza picture Khawar Raza · Jan 22, 2013 · Viewed 44.8k times · Source

I was studying Fragments and got little confused on differentiating FragmentTransaction.replace(id, fragment, tag) and FragmentTransaction.addToBackStack(tag) calls. Lets say that my current fragment is FragmentA and then I loaded FragmentB. I want that in future, when I need to load FragmentA, I don't have to reload it. Just load the old one in old state. I used the following code segment:

public void loadFragment(Fragment fragmentB, String tag) {
    FragmentManager fm = getSupportFragmentManager();
    View fragmentContainer = findViewById(R.id.fragment_container);

    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(fragmentContainer.getId(), fragmentB, tag);

    ft.addToBackStack(tag);

    ft.commit();
}

Now I am confused, where should I add the string tag? In replace() or in addToBackStack() or in both calls? Can you explain the difference between these two tag places?

Answer

gunar picture gunar · Sep 17, 2013

Can you explain the difference between these two tag places?

The documentation for addToBackStack is pretty clear:

An optional name for this back stack state, or null.

While for replace:

Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String).

So these two parameters are independent, one identifies the back stack, while the other identifies the fragment within Activity's FragmentManager.

Your code seems correct from this point of view, just that I would not search the fragmentContainer view by its id, only to use then its id for replacing the fragment. Make it simpler:

public void loadFragment(Fragment fragmentB, String tag) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.fragment_container, fragmentB, tag);

    ft.addToBackStack(null);

    ft.commit();
}

In case you don't need to identify this back stack later on, pass null for addToBackStack. At least I'm always doing it.