Android FragmentTransaction.addToBackStack confusion

▼魔方 西西 提交于 2019-12-03 10:17:53
gunar

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.

Param passed to addToBackStack() can be used to retrieve the whole BackStackEntry object, not just a single fragment. In order to set the fragment tag, consider using 3-param versions of add(int, Fragment, String) and replace(int, Fragment, String)

Prior to adding the Fragment you will be able to check if this Fragment is already in the backstack using :

 getFragmentMangager().findFragmentByTag(SettingsFragment.TAG);

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

Narender Gusain

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!