跳过碎片onBackPressed(添加/隐藏)

时间:2016-06-20 10:18:34

标签: android android-fragments fragmenttransaction onbackpressed fragment-backstack

我正在使用fragmentTransaction来处理片段,它看起来像这样:

        FragmentManager fm = oldFragment.getFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.add(oldFragment.getId(), newFragment, tag);
        fragmentTransaction.hide(oldFragment);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        fragmentTransaction.commit();

有几个片段我想在回去时跳过其中一些。

示例:

  

Frag1 - > (按下一步) - > Frag2 - > (按下一步) - > Frag3 - > (按后退) - > Frag1

此解决方案适用于我使用替换而非添加和隐藏

getFragmentManager().popBackStack(
    tag, 
    FragmentManager.POP_BACK_STACK_INCLUSIVE);

参考文献`Skip some fragments onBackPressed

但在我的情况下,跳过的片段会显示片刻。我怎样才能使它们之间的片段永远不存在?

1 个答案:

答案 0 :(得分:0)

我使用此功能删除碎片告诉我是否有帮助。

public static void removeFragment(FragmentActivity activity) {
    try {
        FragmentManager supportFragmentManager = activity.getSupportFragmentManager(); // getFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.slide_down, R.anim.slide_up);
        fragmentTransaction.remove(supportFragmentManager.getFragments().get(0));

        try {
            fragmentTransaction.commit();

        } catch (Exception e) {
        }
        supportFragmentManager.popBackStack();

    } catch (NullPointerException exception) {
        exception.printStackTrace();
    }
}