PopBackStack无法正常工作

时间:2016-12-23 08:46:46

标签: android android-fragments fragment

我编码如下:

FragA>> FragB>> FragC>> FragD

当我按下FragD的onBackpress()时,它会直接进入FragA,但我想让它继续使用FragC。

BackPress Code:

 if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {
            back_btn.setVisibility(View.GONE);
            getActivity().getSupportFragmentManager().popBackStack();
        }

更换片段代码:

                       FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                       FragmentA fragmentA = new FragmentA();
                       fragmentTransaction.replace(R.id.framelayoutinner, fragmentA);
                       fragmentTransaction.addToBackStack("fragmentA");
                       fragmentTransaction.commit();



                       FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                       FragmentA fragmentB = new Fragmentb();
                       fragmentTransaction.replace(R.id.framelayoutinner_2, fragmentB);
                       fragmentTransaction.addToBackStack("fragmentB");
                       fragmentTransaction.commit();

2 个答案:

答案 0 :(得分:1)

您正在使用嵌套片段,如果您从另一个片段加载片段,那么它将成为嵌套结构。因此,请尝试检查Root片段中是否存在任何子片段,然后首先弹出该子片段。

使用getChildFragmentManager()进行递归调用,直到获得大多数幼儿片段(最后添加)。或者更好地在片段上使用标记

答案 1 :(得分:0)

您需要使用addToBackStack方法将每个片段添加到Backstack中

  public void setmFragmentContainer(Fragment fragment)
    {
        final String tag = fragment.getClass().getName();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.layout_content, fragment, tag);
        transaction.addToBackStack(tag);
        transaction.commit();
    }

此方法可以帮助您