How to fix OnBackPressedCallback if it doesn't work in Fragment?

372 Views Asked by At

Here I override handleOnBackPressed() method:

 Log.d("Fragment", "onViewCreated")
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    Log.d("Fragment", "Back pressed")
                    if (binding.crimeTitle.text.isBlank()) {
                        Toast.makeText(context, "Title can't be empty!", Toast.LENGTH_SHORT).show()
                        Log.d("Fragment", "Toast showed")
                    } else {
                        Log.d("Fragment", "BackStack popped")
                        findNavController().popBackStack()
                    }
                }
            }
        }

But after that I see only "onViewCreated" in Logs and nothing happens after pressing "Back" button.
I expected to see at least "Back pressed".
Witout this part of code "Back" button works as usual.
Logs:
(https://i.stack.imgur.com/bAmxq.png)

1

There are 1 best solutions below

0
Viktor On

Finally, I've found a solution.
It's important to add that callback in "onCreate" function of Fragment, otherwise "Back" button won't react on your actions. And owner in "addCallback(owner)" have to be "this", If you try to pass "viewLifecycleOwner" you'll get an exception:

FATAL EXCEPTION: main
java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()