How to handle back button when using Nested Fragments in Android

552 Views Asked by At

I have a Home fragment with multiple buttons and when I click the Contact button, another fragment is opened. Inside this fragment I have two child fragments and two buttons, and I can switch between those child fragments using those buttons. The problem is when I press the Back Button, it switches back between child fragments and only after that it goes back to Home fragment, but I want to directly go back to Home Fragment.

This is how I'm opening the child fragments:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val contactsListFragment = ContactsListFragment()
    val groupsListFragment = GroupsListFragment()

    activity?.title = getString(R.string.contacts_and_groups)
    openChildFragment(contactsListFragment)

    binding.contactsButton.setOnClickListener {
        openChildFragment(contactsListFragment)
    }

    binding.groupsButton.setOnClickListener {
        openChildFragment(groupsListFragment)
    }
}

private fun openChildFragment(fragment: Fragment) {
    val childFragmentManager = childFragmentManager
    val transaction: FragmentTransaction = childFragmentManager.beginTransaction()
    transaction.replace(binding.contactsGroupsFl.id, fragment)
    transaction.addToBackStack(null)
    transaction.commit()
}

If anyone can help me with this issue would be great. Thanks!

1

There are 1 best solutions below

0
On

I think you should add a listener for the back button in both of your fragments so that you can clear all the backstack when it's pressed. Something like this :

requireActivity().onBackPressedDispatcher.addCallback(
    viewLifecycleOwner,
    object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            for (i: Int in 1..parentFragmentManager.backStackEntryCount) {
                parentFragmentManager.popBackStack()
            }
        }
    })