Listen to Back Button Clicks in Fragment

Listening to the back button click event inside the fragments, comprised of a painful implementation of the interfaces and the onBackPressed method calls in both Activity and Fragment, prior to the introduction of the OnBackPressedDispatcher.

But now, inside a Fragment, the back button behaviour can be controlled by listening to the callback returned by the OnBackPressedDispatcher. This callback listener is implemented inside the onCreate overridden method.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Listen to Back button clicks
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }
}
Use onBackPressedDispatcher method to get the OnBackPressedDispatcher and add the callback using the addCallback method. This callback method takes a lifecycle owner.

Handle the back button events whenever the callback gets triggered. The same implementation can be done in the Activities onCreate method.

Since we are passing the lifecycle owner to the callback, it is removed automatically when the lifecycle owner gets destroyed. Incase, we want to remove the callbacks manually, we can do so using the method
callback.remove()
In case there is an existing implementation of onBackPressed overridden method call in your Activity or Fragment replace it with the OnBackPressedDispatcher.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Mr Phone - Find The Next Best Phone You Want To Buy

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment

Create Assets Folder, Add Files and Read Data From It