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 ??
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the
FragmentManager
and its backstack. Here's how you can do it:Now instead of adding and removing fragments by calling
FragmentManager
directly, you should usepush()
,replace()
, andpop()
methods ofFragmentStackManager
. And you will be able to access the topmost fragment by just callingstack.get(stack.size() - 1)
.But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which
addToBackStack
has been called:Please notice that in this case you have to put this class into
android.support.v4.app
package.