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 ??
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
Finally, you can find any of your fragments in your backstack with this method:
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
Hope this helps!
You can use the
getName()
method ofFragmentManager.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 withaddTobackStack(tag)
.You need to make sure that you added the fragment to the backstack like this:
function returns link to top
Fragment
in backstack. Usage example:The answer given by deepak goel does not work for me because I always get null from
entry.getName()
;What I do is to set a Tag to the fragment this way:
Where ft is my fragment transaction and
FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
*This should be called from inside an Activity.
Enjoy :)
Keep your own back stack:
myBackStack
. As youAdd
a fragment to theFragmentManager
, also add it tomyBackStack
. InonBackStackChanged()
pop frommyBackStack
when its length is greater thangetBackStackEntryCount
.