Android 4.2: back stack behaviour with nested fragments

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

    This solution may be better version of @Sean answer:

    @Override
    public void onBackPressed() {
        // 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
        FragmentManager fm = getSupportFragmentManager();
        for (Fragment frag : fm.getFragments()) {
            if (frag.isVisible()) {
                FragmentManager childFm = frag.getChildFragmentManager();
                if (childFm.getBackStackEntryCount() > 0) {
                    childFm.popBackStack();
                    return;
                }
            }
        }
        super.onBackPressed();
    }
    

    Again, I prepared this solution based on @Sean answer above.

    As @AZ13 said, this solution is only feasible in one level child fragments situations. In multiple level fragments case, works become a little complex, so I recommend that try this solution only the feasible case I have said. =)

    Note: Since getFragments method is now a private method, this solution will not work. You can check comments for a link which suggests a solution about this situation.

提交回复
热议问题