4

I need to make a custom behaviour, when the user press the back button then the user will go to certain destination programatically. I actually have read this Handling back button in Android Navigation Component

but I don't understand how to use that custom back button code.it seems weird to me.

I have tried using this code below

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        fragmentView = inflater.inflate(R.layout.fragment_search_setting, container, false)

        // set custom back button
        val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {

            // navigate to certain destination
            Navigation.findNavController(fragmentView).popBackStack(R.id.destination_create_event, false)


        }


        return fragmentView
    }

but I get type mismatch error like this enter image description here

Alexa289
  • 8,089
  • 10
  • 74
  • 178

1 Answers1

3

You must create new Instance of the OnBackPressedCallback abstract class and implement its abstract method .

I hope this helps you:

        val callback = requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
                        Navigation.findNavController(fragmentView).popBackStack(R.id.destination_create_event, false)
        }


    })

    // The callback can be enabled or disabled here or in the lambda

}
ahooee
  • 275
  • 3
  • 14
  • This is not what the OP is asking. The OPs code is fine; I think it's using the wrong imports. – Martin Marconcini Oct 06 '19 at 12:14
  • @MartinMarconcini As you can see in the screenshot , a type mismatch error eccurs and the error message says an OnBackPressedCallback required but found boolean – ahooee Oct 06 '19 at 12:32
  • @ahooee i've tried your solution, but I have error like this https://i.stack.imgur.com/imLjY.png – Alexa289 Oct 07 '19 at 00:11
  • @Alexa289 Just add the closing addCallback function parenthesis before 'return fragmentView' statement .see the screenshot: [ScreenShot](https://drive.google.com/file/d/1MGKQ9Ns8VCVZ4zQoYkDnsmph9Sn3Wmkb/view) – ahooee Oct 07 '19 at 03:10