Whats the fuss about OnBackPressedDispatcher

Vairavan Srinivasan
1 min readSep 24, 2019

Recent versions of Android X has had quite a few updates about handling back press event especially when dealing with hosted Fragments within Activity. So whats the fuss about it?

Here is a typical usage of handling back press in an activity to intercept and dismiss Navigation View, if open.

override fun onBackPressed() {
if(drawerLayout.isDrawerOpen(navView)) {
drawerLayout.closeDrawers()
} else {
super.onBackPressed()
}
}

In the world of OnBackPressedDispatcher, it is replaced with this one time setup from onCreate.

The logic to dismiss the navigation view is implemented as a callback of instance OnBackPressedCallback and is registered using Activity’s onBackPressedDispatcher. The conditional logic is implemented by enabling or disabling the callback. In this case, it is enabled as soon when the Navigation View is opened.

Quite a verbose code but really shines when used with Fragments.

--

--