1

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 ?

Zhen Jing Heng
  • 109
  • 2
  • 8

1 Answers1

4

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.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34