Zhen Jing Heng
Zhen Jing Heng

Reputation: 109

PopBackStack previous last fragment and check which fragment it is

I got a few fragments in MainActivity which can be selected from Navigation Drawer. Now, whenever users press a profile button, it will jumps to UserProfile Fragment. If home button is pressed, it will pop back the last fragment. Since I've assigned each of the fragments a specific backstack name i.e .addToBackStack("abc"), how can I check what is the last fragment by using popBackStack() method ?

Upvotes: 1

Views: 2643

Answers (1)

tahsinRupam
tahsinRupam

Reputation: 6405

To get the last fragment:

FragmentManager fm = getSupportFragmentManager();
int lastFragEntry = fm.getBackStackEntryCount()-1;
String lastFragTag = fm.getBackStackEntryAt(lastFragEntry).getName();

Log.i("Last Fragment Tag->", lastFragTag);

NB: If you want to get the name/tag of last fragment, you also have to use the same Tag during fragment transaction:

ft.replace(android.R.id.container, fragment, "abc");
ft.addToBackStack("abc");

Hope this helps.

Upvotes: 4

Related Questions