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 ?
Asked
Active
Viewed 2,484 times
1

Zhen Jing Heng
- 109
- 2
- 8
1 Answers
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
-
1Thanks! You saved me :D – Zhen Jing Heng Mar 26 '17 at 21:09
-
My pleasure. :) – tahsinRupam Mar 26 '17 at 21:25