Android FragmentTransaction.addToBackStack confusion Android FragmentTransaction.addToBackStack confusion android android

Android FragmentTransaction.addToBackStack confusion


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.


In this example you don't need to add tags as identification.Just do:

ft.replace(R.id.fragment_container,fragmentB);ft.addToBackStack(null);ft.commit();

The tag as identification is commonly used when you want to add a fragment without a UI.


Passing null to addtoBackStack(null) means adding the fragment in the Fragment Stack but not adding any TAG which could be further use to identify the particular fragment in a stack before adding again.

    .addToBackStack(null);

But passing TAG to addToBackStack helps in identifying the fragment in Fragment stack by TAG.Like

.addToBackStack(FragmentName.TAG);

Now we can check the fragment before adding it to the Stack :

 getFragmentManager().findFragmentByTag(SettingsFragment.TAG);

This will return null if the Fragment is not already added.