How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?
FragmentManager fragManager = activity.getSupportFragmentManager(); FragmentTransaction fragTransacion = fragMgr.beginTransaction(); /****After add , replace fragments (some of the fragments are add to backstack , some are not)***/ //HERE, How can I get the latest added fragment from backstack ??
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1 FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index); String tag = backEntry.getName(); Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With