Search code examples
androidkotlinandroid-architecture-componentsandroid-jetpackandroid-architecture-navigation

how to make custom back button to go back to certain destination using navigation controller in Android?


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


Solution

  • 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
    
    }