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 ??
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
Java:
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
this helper method get fragment from top of stack: