简体   繁体   中英

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

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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM