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
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