简体   繁体   English

从ViewPager中的嵌套片段向后导航

[英]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). 对于每个指令(FragmentA),用户可以导航到另一个屏幕(FragmentA1)。 I have used a ViewPager that hold list of fragments. 我使用了一个ViewPager,它保存片段列表。 When user navigates to the first fragment(FragmentA) the user can click a button and move to a (FragmentA1) detailed view of the instruction. 当用户导航到第一个片段(FragmentA)时,用户可以单击按钮并移至指令的(FragmentA1)详细视图。 So each page of the viewpager is capable of opening another fragment. 因此,viewpager的每个页面都可以打开另一个片段。

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. 使用viewpager适配器的活动处理moveToNext()和moveToPrevious()方法。 Below is my implementation of onBackPressed() method: 下面是我的onBackPressed()方法的实现:

 @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. 上面的实现是:如果我遍历FragA-> FragA1-> FragB-> FragB1-> FragC-> FragC1当我在FragC1并按返回按钮时,那么我将直接导航到FragB1而不是FragC,再导航到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 ? fm.popBackStack()是否不显示父片段?

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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