Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackStack is not working with nested Fragments

I'm using ViewPager to show three pages as fragments FirstFragment, SecondFragment, ThirdFragment:

In first page of ViewPager that is FirstFragment, on a button click I'm moving to FragmentA, then in FragmentA on a button click I'm moving to FragmentB, them in FragmentB on a button click, I'm moving to fragment C. Now when I will press back key, I want to come in following order: FragmentC, then FragmentB, then FragmentA, then FirstFragment(ViewPager first page)

But when I'm pressing back key on FragmentC, I'm exiting the app:

Then I used the following solution

@Override
public void onBackPressed() {
    // if there is a fragment and the back stack of this fragment is not empty,
    // then emulate 'onBackPressed' behaviour, because in default, it is not working
    FragmentManager fm = getSupportFragmentManager();
    for (Fragment frag : fm.getFragments()) {
        if (frag.isVisible()) {
            FragmentManager childFm = frag.getChildFragmentManager();
            if (childFm.getBackStackEntryCount() > 0) {
                childFm.popBackStack();
                return;
            }
        }
    }
    super.onBackPressed();
}

The above solution is working only if I'm having FirstFragment(ViewPager First Page) then FragmentA

But this is not working in case of nested fragments: FirstFragment(ViewPager First Page) then FragmentA, then FragmentB, then FragmentC

like image 620
kittu Avatar asked Feb 21 '26 15:02

kittu


1 Answers

I solved this issue by using the following way:

In ViewPager FirstFragment, for adding first nested fragment that is FragmentA, I used getChildFragmentManager.

But in FragmentA on a button click, for adding FragmentB and, in FragmentB on a button click for adding FragmentC, for both I used getSupportFragmentManager.

Also used following onBackPressed method:

@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    for (Fragment frag : fm.getFragments()) {
        if (frag.isVisible()) {
            FragmentManager childFm = frag.getChildFragmentManager();
            if (childFm.getBackStackEntryCount() > 0) {
                for (Fragment childfragnested: childFm.getFragments()) {
                    FragmentManager childFmNestManager = childfragnested.getFragmentManager();
                    if(childfragnested.isVisible()) {
                        childFmNestManager.popBackStack();
                        return;
                    }
                }
            }
        }
    }
    super.onBackPressed();
}
like image 64
kittu Avatar answered Feb 24 '26 08:02

kittu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!