Android : Return to previous fragment on back press

前端 未结 5 1357
南笙
南笙 2021-02-12 17:44

I have implemented Navigation Drawer which is a subclass of Activity. I have many fragments in my application. My question goes here

Imagine there are 3 fragments :

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 18:37

    The tric is in FragmentManager#executePendingTransactions();.

    This is what I use for nested fragments as well...:

    /**
     * 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
     */
    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;
    }
    

    and in my onBackPressed :

                    if (!FragmentUtils.dispatchOnBackPressedToFragments(fm)) {
                        // if no child fragment consumed the onBackPressed event,
                        // we execute the default behaviour.
                        super.onBackPressed();
                    }
    

提交回复
热议问题