Navigating with BottomNavigationViews

You know those BottomNavigationView’s that are more commonplace in Android apps these days?

Recently, I’ve been building a small sample app for a PluralSight course I’m working on that has one of these BottomNavigationView’s and it wasn’t apparently obvious to me how I should be switching the actual views that are on screen as the user taps through various items in the bottom menu. A simple Google search didn’t answer my question either since most blog posts and StackOverflow answers on the subject matter did one of the following:

  1. Simply introduced the BottomNavigationView and left it at that
  2. Switched the views using a ViewPager but when I downloaded the sample app, the effect seemed a bit weird
  3. Recommended starting up an entire Activity every time a user tapped on a new menu item, but I didn’t like that since that meant you had to re-inflate the bottom navigation view every time. Also, when I implemented it that way, there seemed to be a bit of a lag every time I tapped on a new item.

Thus, I decided to implement the switching of BottomNavigationView menu items by inflating appropriate Fragments into the view. And now… let’s go over the code on how to implement this 🙂

First, our XML layout

And our content_main.xml file

And the bottom_navigation_menu file

These two layout files and the menu item xml file will give us a screen that looks something like this.

Now, what we want to implement is the actual switching of the screen in display. The screen in-display is actually the fragment that is inflated from the MainActivity. Also, when the user taps on a bottom menu item, we want the appropriate fragment to take place of the previous fragment. Here’s how we do it.

In the code, you can see that I inflate a new HomeFragment, which is the default fragment in my code sample automatically, which I store into a mCurrentFragment variable. And based on what the user taps on the BottomNavigationView (which I have a listener set on), I store the appropriate newly instantiated fragment to the mCurrentFragment variable and display that fragment instead.

So far, this is the simplest and most modular way I could think of to get this working. Google docs didn’t seem to have recommended approaches, and blog posts online didn’t have solutions that I liked. The solution that seemed to give the most fluidity that didn’t use fragments like I do involved simply hiding and then displaying certain elements in the layout file depending on which menu item was active. I didn’t like this since that meant unnecessary code will have to be run all at once, potentially causing memory problems.