My app contains two tabs, inside two tabs every tab has 4-5 nested fragments, inside nested fragments addtobackstack is not working? How can I add nested fragments to backstack because when I click back button inside nested fragments my app is closing means it's calling super.onBackKeyPressed method.
Asked
Active
Viewed 885 times
3 Answers
3
Add this code in your activity
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getFragments() != null) {
for (Fragment frag : fm.getFragments()) {
if (frag.isVisible()) {
FragmentManager chilFrag = frag.getChildFragmentManager();
if (chilFrag.getBackStackEntryCount() > 0) {
chilFrag.popBackStack();
return;
}
}
}
}
super.onBackPressed();
}

William Reed
- 1,717
- 1
- 17
- 30

Bhanu Prakash Pasupula
- 962
- 2
- 9
- 25
1
You should use ChildFragmentManager
This is fragment replace function.
fun replace(fragment: Fragment){
childFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.commit()
}
And override onBackPressed method in most parent fragment.
override fun onBackPressed() {
val pop = childFragmentManager.popBackStackImmediate()
if (!pop){
super.onBackPressed()
}
}
I wrote with kotlin i hope you can understand.If you need more info, please ask to me.

Kemal Turk
- 2,160
- 1
- 14
- 15
-
Can you elaborate more? – Bhanu Pro Apr 30 '18 at 06:49
-
should I use inside viewpager or nested fragments? – Bhanu Pro Apr 30 '18 at 06:50
0
Use ChildFragmentManager
and check if active tab has BackStackEntry
, if so then pop backstack else call super.onBackKeyPressed
complete description on this answer: https://stackoverflow.com/a/37961649/4832356

SiSa
- 2,594
- 1
- 15
- 33