Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1806
爱一瞬间的悲伤
爱一瞬间的悲伤 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:39

    Thanks to everyone for their help, this (tweaked version) works for me:

    @Override
    public void onBackPressed() {
        if (!recursivePopBackStack(getSupportFragmentManager())) {
            super.onBackPressed();
        }
    }
    
    /**
     * Recursively look through nested fragments for a backstack entry to pop
     * @return: true if a pop was performed
     */
    public static boolean recursivePopBackStack(FragmentManager fragmentManager) {
        if (fragmentManager.getFragments() != null) {
            for (Fragment fragment : fragmentManager.getFragments()) {
                if (fragment != null && fragment.isVisible()) {
                    boolean popped = recursivePopBackStack(fragment.getChildFragmentManager());
                    if (popped) {
                        return true;
                    }
                }
            }
        }
    
        if (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStack();
            return true;
        }
    
        return false;
    }
    

    NOTE: You will probably also want to set the background color of these nested fragments to the app theme's window background color, as by default they are transparent. Somewhat outside of the scope of this question, but it is accomplished by resolving the attribute android.R.attr.windowBackground, and setting the Fragment view's background to that resource ID.

提交回复
热议问题