1

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bhanu Pro
  • 55
  • 7

3 Answers3

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
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
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