Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1821
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 16:01

With Android 4.2, the support library got support for nested fragments see here. I\'ve played around with it and found an interesting behaviour / bug regarding back stack an

17条回答
  •  隐瞒了意图╮
    2020-11-29 16:35

    This solution may be better, bacause it checks all the levels of nested fragments:

     /**
     * This method will go check all the back stacks of the added fragments and their nested fragments
     * to the the {@code FragmentManager} passed as parameter.
     * 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.
     *
     * @param fm the fragment manager to which we will try to dispatch the back pressed event.
     * @return {@code true} if the onBackPressed event was consumed by a child fragment, otherwise {@code false}.
     */
    public static boolean dispatchOnBackPressedToFragments(FragmentManager fm) {
    
        List fragments = fm.getFragments();
        boolean result;
        if (fragments != null && !fragments.isEmpty()) {
            for (Fragment frag : fragments) {
                if (frag != null && frag.isAdded() && frag.getChildFragmentManager() != null) {
                    // go to the next level of child fragments.
                    result = dispatchOnBackPressedToFragments(frag.getChildFragmentManager());
                    if (result) return true;
                }
            }
        }
    
        // if the back stack is not empty then we pop the last transaction.
        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
            fm.executePendingTransactions();
            return true;
        }
    
        return false;
    }
    

    in your activity onBackPressed you can simply call it this way:

    FragmentManager fm = getSupportFragmentManager();
                    // 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
                    if (!dispatchOnBackPressedToFragments(fm)) {
                        // if no child fragment consumed the onBackPressed event,
                        // we execute the default behaviour.
                        super.onBackPressed();
                    }
    

提交回复
热议问题