How to handle Bottom Navigation perfectly with back pressed?

Looking at the YouTube app, did you also want to do the same bottom navigation as there? Creating a similar interface is not such a difficult task, the logic of pressing is another thing.

The default implementation of pressed back button simply finishes the current activity. The search for possible solutions to implement navigation in the backward direction when it calling give me only something like this:

If last selected item is not home then go to it. But that’s not enough, right?

Let’s take a look how to make the same logic like on YouTube App.


What we gotta do?

We will use memorizing-pager library that contain extended ViewPager. Setting up MemorizingPager with BottomNavigationView will allow us to navigate in the opposite direction of selected items history.

Project setup

First, you have to import the library to your Android project.

Add the JitPack repository to your root build.gradle at the end of repositories.

Then add the dependency to your application-level build.gradle (Make sure that you are using the latest version. At the time of publication it’s 1.1.1)

Adding layout

To begin, create a layout with a MemorizingPager and then setup properties. An example is shown below.

XML

Init

For MemorizingPager do it as you always do.

For disabling BottomNavigationView shift mode use the helper class. (You will need to execute this method each time you change menu items in your BottomNavigationView)

Setting up listeners

We can implement listeners of ViewPager and BottomNavigationView in MainActivity and setting up them with this keyword like in the code above.

Activity.onBackPressed

BottomNavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener

In this example for more clean code we use item.getOrder() instead of item.getItemId() with switch statement. We can do it because of we setup menu items property android:orderInCategory with values from 0 to numPages. (0, 1, 2, 3 in my case)

Result:


If you want to use NavigationHistory independent of ViewPager see Wiki or demo app. Feel free to make use of this library, and help me improve it over on GitHub, link below.

Links:


If you enjoyed reading this article, it would mean a lot if you show your support using the 👏 clapping icon and share with your colleagues and friends.
Thanks and happy coding!