Posts

Showing posts from January, 2021

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