Back press handling with AndroidX Navigation component

Alex Maryin
2 min readJun 3, 2021
Photo by DDP on Unsplash

When you create your android application with single-activity style implementing all of application screens by Fragments, you can not intercept “back” press event because of Fragment haven’t onBackPressed method to override as Activity has.

In sad world without Navigation Component we should provide an Interface like HasBackPressedCallback, implement by our Fragments this interface and manage in Activity onBackPressed method invoking of that callback for shown fragment.

But! Our awesome world already has Navigation Component, so we don’t need all of that boilerplate code for interfaces and its implementing as far as handmade handling process with fragment’s manager. All of you need is to add a custom backPress callback to backPressedDispatcher of the fragment.

Supppose we build an application which shows different lists of items with RecyclerView. Most likely we shall use only one fragment with one RecyclerView but with different ViewHolders according to the type of chosen items (on bottom bar or menu).

Ordinary user may want to navigate from one list to other and back with pressing hard-key “back” or swiping same gesture. But as far as all of lists rendered by only one fragment on single activity pressing the “back” shall make activity destroy and application closes.

Many developers provide a confirmation dialog to close the app or short interval to close by double-clicking back with showing a toast like “Press again to exit”.

It’s a really simple to feature this with Kotlin or Java in android application supporting Navigation component! We need only to imlement OnBackPressedCallback interface by any class or object like this:

In this handler we create an object implementing OnBackPressedCallback and enable it (“true” in parameter). You might create multiple handlers for back press and backPressedDispatcher shall manage them with chain-of-responsibility pattern, so the first enabled handler will be invoked and disabled handlers be skiped.

It’s important to note that multiple handlers are invoked in reversed order, not which they were added.

At the end we need to add callback to dispather in onCreateView method of fragment:

It’s all! In this example if user navigates back from any screen (any list of items in recyclerView) different of MainScreen, this main screen shall be rendered instead of app close. In case of main screen it will toast a hint “Press again to exit” and wait for 2 seconds for double back press.

Thank you for reading.

--

--

Alex Maryin

My profession is lawyer, but I like programming for a whole my life. It started since 90's with ZX-spectrum, and now I fan of Kotlin, Python, Pascal & C++.