Android 4.2: back stack behaviour with nested fragments

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

    I solved this issue by keeping currently opened fragment in property of activity. Then I override method

     // INSIDE ACTIVITY
     override fun onBackPressed() {
        val fragment = currentFragment
    
        if(fragment != null && fragment.childFragmentManager.fragments.any()){
            fragment.childFragmentManager.popBackStack()
        }
        else {
            super.onBackPressed()
        }
    }
    

    This is how I add child fragment into currently opened fragment from within itself.

     // INSIDE FRAGMENT
     menu_fragment_view.setBackgroundColor(-((Math.random() * 10000 ).toInt() % 30000)) // to see change
     add_fragment_button.setOnClickListener {
            val transaction = childFragmentManager.beginTransaction()
    
            transaction.add(R.id.menu_fragment_fragment_holder, MenuFragment())
    
            transaction.addToBackStack(null)
    
            transaction.commit()
        }
    

    This is xml layout of parent fragment and added fragment

     
     
         

提交回复
热议问题