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.
memorizing-pager - Custom ViewPager which allows navigating in the opposite directiongithub.com
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)
To begin, create a layout with a MemorizingPager and then setup properties. An example is shown below.
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.
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)
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!