Android 4.2: back stack behaviour with nested fragments

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

    The real answer to this question is in the Fragment Transaction's function called setPrimaryNavigationFragment.

    /**
     * Set a currently active fragment in this FragmentManager as the primary navigation fragment.
     *
     * 

    The primary navigation fragment's * {@link Fragment#getChildFragmentManager() child FragmentManager} will be called first * to process delegated navigation actions such as {@link FragmentManager#popBackStack()} * if no ID or transaction name is provided to pop to. Navigation operations outside of the * fragment system may choose to delegate those actions to the primary navigation fragment * as returned by {@link FragmentManager#getPrimaryNavigationFragment()}.

    * *

    The fragment provided must currently be added to the FragmentManager to be set as * a primary navigation fragment, or previously added as part of this transaction.

    * * @param fragment the fragment to set as the primary navigation fragment * @return the same FragmentTransaction instance */ public abstract FragmentTransaction setPrimaryNavigationFragment(Fragment fragment);

    You have to set this function on the initial parent fragment when the activity is adding it. I have a replaceFragment function inside of my activity that looks like this:

    public void replaceFragment(int containerId, BaseFragment fragment, boolean addToBackstack) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setPrimaryNavigationFragment(fragment);
        if (addToBackstack) {
            fragmentTransaction.addToBackStack(fragment.TAG);
        }
    
        fragmentTransaction.replace(containerId, fragment).commit();
    }
    

    This gives you the same behavior as if your clicking back from regular Fragment B back to Fragment A, except now it is on the child fragments as well!

提交回复
热议问题