Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1852
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 16:54

    The reason is that your Activity derives from FragmentActivity, which handles the BACK key press (see line 173 of FragmentActivity.

    In our application, I'm using a ViewPager (with fragments) and each fragment can have nested fragments. The way I've handled this is by:

    • defining an interface OnBackKeyPressedListener with a single method void onBackKeyPressed()
    • implemented this interface in "top" fragments that ViewPager shows
    • overriding onKeyDown and detecting BACK press, and calling onBackKeyPressed in a currently active fragment in the view pager.

    Also note, that I'm using getChildFragmentManager() in the fragments to properly nest fragments. You can see a discussion and an explanation in this android-developers post.

提交回复
热议问题