Android 4.2: back stack behaviour with nested fragments

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

    After observing some solutions presented here, I found that to allow flexibility & control for the parent fragment as to when popping the stack or when the back action should be ignored by it, I rather use such implementation:

    Defining a "ParentFragment" interface:

    interface ParentFragment {
    /**
     * Fragments that host child fragments and want to control their BackStack behaviour when the back button is pressed should implement this
     *
     * @return true if back press was handled, false otherwise
     */
    fun onBackPressed(): Boolean
    

    }

    Overriding the "onBackPressed" in the parent activity (or in the BaseActivity):

    override fun onBackPressed() {
        val fm: FragmentManager = supportFragmentManager
        for (frag in fm.fragments) {
            if (frag.isVisible && frag is ParentFragment && frag.onBackPressed()) {
                return
            }
        }
        super.onBackPressed()
    }
    

    And then allow the parent fragment to handle as it wishes, for example:

    override fun onBackPressed(): Boolean {
        val childFragment = childFragmentManager.findFragmentByTag(SomeChildFragment::class.java.simpleName)
        if (childFragment != null && childFragment.isVisible) {
            // Only for that case, pop the BackStack (perhaps when other child fragments are visible don't)
            childFragmentManager.popBackStack()
            return true
        }
        return false
    }
    

    This allows to avoid thinking that there is some legitimate child fragment to remove when using a view pager for example (and back stack entry count > 0).

提交回复
热议问题