Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the latest fragment in backstack

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 ?? 
like image 847
Leem.fin Avatar asked Mar 14 '12 12:03

Leem.fin


People also ask

How do you find current fragments?

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.


1 Answers

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); 
like image 84
Deepak Goel Avatar answered Sep 29 '22 12:09

Deepak Goel