简体   繁体   中英

Navigating back from nested fragments in ViewPager

I need to display multiple set of instructions to the user. For each instruction(FragmentA) the user can navigate to another screen (FragmentA1). I have used a ViewPager that hold list of fragments. When user navigates to the first fragment(FragmentA) the user can click a button and move to a (FragmentA1) detailed view of the instruction. So each page of the viewpager is capable of opening another fragment.

All works fine till here. Issue I am facing is with the backstack. The activity with the viewpager adapter handles the moveToNext() and moveToPrevious() methods. Below is my implementation of onBackPressed() method:

 @Override
public void onBackPressed() {

    FragmentManager fm = getSupportFragmentManager();
    for (Fragment frag : fm.getFragments()) {
        if (frag.isVisible()) {
            FragmentManager fm = frag.getFragmentManager();
            if (fm.getBackStackEntryCount() > 0) {
                fm.popBackStack();
                return;
            } else {
                moveToPrevious();
                return;
            }
        }
    }
    super.onBackPressed();
}

With the above implementation is: If I traverse FragA->FragA1->FragB->FragB1->FragC->FragC1 When I am at FragC1 and I press back button, then I am directly navigated to FragB1 instead of FragC and then to FragA1. I need to follow the same path backwards as traversed forward.

I am not sure what is wrong but it is not able to pop the nested fragment and display its parent fragment. Shouldn't fm.popBackStack() show the parent fragment ?

I solved it this way. Get the fragment that is visible. When there are no child fragments to pop anymore just move to previous page.

 @Override
public void onBackPressed() {
    FragA fragment = (FragA) pagerAdapter.instantiateItem(viewPager, viewPager.getCurrentItem());

    if (fragment.getChildFragmentManager().getBackStackEntryCount() != 0) {
        fragment.getChildFragmentManager().popBackStack();
    }
    else {
        moveToPrevious();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM