0

All the Fragment inherits from BaseFragment.

And I'd like to give back press event respectively to each fragment. But BaseFragment has default back press event like this.

    override fun onResume() {
        super.onResume()
        logd("onResume() BaseFragment")
        requireActivity().onBackPressedDispatcher.addCallback(this, backPressCallback)
    }

And also the child fragments have

    override fun onResume() {
        super.onResume()
        logd("onResume() ChildFragment")
        requireActivity().onBackPressedDispatcher.addCallback(this, backPressCallback)
    }

It will print,

onResume() BaseFragment
onResume() ChildFragment

So, the ChildFragment override and when I press back button, ChildFragment's backPressCallback is called.

However, when I go out and come back, the order is different.

onResume() ChildFragment
onResume() BaseFragment

So, the user sees ChildFragment but BaseFragment's backPressCallback is called. And it behaves different from what I expected. (ex. I want popBackStack but close the app)

How can I solve this problem? Or is there any method that called after the parent fragment is called?

According to this article, BaseFragment must be called before ChildFragment. But it doesn't seem so.

c-an
  • 3,543
  • 5
  • 35
  • 82

1 Answers1

0
    activity?.onBackPressedDispatcher?.addCallback(
                    viewLifecycleOwner,
                    object : OnBackPressedCallback(true) {
                        override fun handleOnBackPressed() {
                            try {
                                if (!isChildFragmentOpen)
                                {
                                    val trans: FragmentTransaction =
                                        parentFragmentManager.beginTransaction()
                                    trans.remove(Fragment())
                                    trans.commit()
                                }else{
                                    parentFragmentManager.popBackStack()
                                } 
                            } catch (e: Exception) {
                                e.message
                            }
                        }
                    })

add this to your fragment.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36