Bottom Navigation Bar Android Tutorial

One of the newest additions to the Material Design is the Bottom Navigation Bar. Its like the TabBar you see on iOS, and similar in functionality too.

android bottom navigation tabs

Android Bottom Navigation

facebook iOS app tabbar

Facebook iOS App

 

NOTE:
If you’re looking for a simpler solution, Android now officially supports Bottom Navigation. It is a part of the Design Support Library.

Before getting to the tutorial, let’s get to know what Bottom Navigation is. Also let’s narrow down on the best scenarios to use it.

What is Bottom Navigation?

Bottom navigation bars make it easy to explore and switch between top-level views in a single tap. – Material Design spec

Again, iOS users would feel completely at home with this, since its exactly the same.

This helps developers opt for Bottom Navigation, instead of a Navigation Drawer. If you have about four top-level navigation items, its ideal to use Bottom Navigation. Otherwise, go for a Navigation Drawer. We don’t want the Bottom Navigation looking too crowded now, do we?

When to use?

Best used when you have three to five top-level navigation items of similar importance.

Until now, the default, go-to navigation solution is the Navigation Drawer. Would you agree?

Grab all your screens, throw them in the Navigation Drawer and we’re done. I don’t blame you. Once upon a time, I was guilty of the same.

For just 4 navigation screens, would you use an entire Navigation Drawer for it? Besides, that huge side menu is hidden away by a tiny hamburger menu.

Think of the benefits a Bottom Navigation provides:

  • always visible – its omnipresent no matter which of the 4 screens you visit
  • simpler – lesser the options, easier to remember

So given all that, in such a scenario, a Bottom Navigation will serve you the best.

A simpler way to look at it

If all that seems too complex, then just keep the number of navigation screens in mind.

  • 2 screensTabs
  • 3 to 5 screens – Bottom Navigation
  • 5 and above – Navigation Drawer

Easy enough? Now let’s move on.


Getting Started

Yet with all that aside, I must admit the Bottom Navigation looks pretty cool. So right when I started to make it, I noticed Aurelien Hubert’s library for the same. That was a godsend! So let’s get right to using that.

Add the library’s dependency to your build.gradle file.

dependencies {
    compile 'com.aurelhubert:ahbottomnavigation:0.1.3'
}

NOTE:
This library support minSDK 14 and above only.

Adding Bottom Navigation to Layout

Make sure your parent layout is a CoordinatorLayout. This ensures the Bottom Navigation behaves correctly with Snackbar and FAB.

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:background="#EFEFEF"/>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

</android.support.design.widget.CoordinatorLayout>

The FrameLayout with ID @+id/frame is the placeholder UI to load our Fragment.

Moving onto Java

Each Bottom Navigation bar item denotes a different color. For demonstration purposes, each item click will change the Fragment’s view color. But ideally, you’ll want to load a different Fragment for each item.

Initializing and using the Bottom Navigation is easy as one two three. I ain’t even kidding. See for yourself!

1. Create your Items

There are different constructors you can use to define your Bottom Navigation items.

At the least, you must provide a title and icon. In other words, a String and Drawable.

Both parameters can be hardcoded Strings. But for the sake of good practice, lets reference both from XML resources.

AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.bottomnav_title_0, R.drawable.ic_map_24dp);

 2. Add Bottom Navigation items

Once you’ve defined the number of items, its time to add them to the Bottom Navigation.

Use the following method to do so.

bottomNavigation.addItem(item1);

 3. Set Listener

Finally, you need to listen to item clicks. So add the following to your Fragment.

bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
          @Override
          public void onTabSelected(int position, boolean wasSelected) {
              fragment.updateColor(Color.parseColor(colors[position]));
          }
      });

I have a tiny card layout centered in my Fragment layout. Depending on the item click, I change its color.

Also, don’t forget to set your default item. This item depicts the default (home) screen which people will see.

// Setting the very 1st item as home screen.   
bottomNavigation.setCurrentItem(0);

Ideally, you’d want to change the Fragment here. The same way when creating a Navigation Drawer in Android.


Styling Bottom Navigation

Off the bat, the library provides considerable styling options. But after recent updates, there has been a lot more.

Some of these additions include notification badges and coordinating behaviors. It also includes on-scroll Quick Return pattern.

Its all that one could ever want with the Bottom Navigation. This library is much more feature-rich than what Android Design Support Library offers. So if you want more customization options and more control, you know what to use.

Before we get to that, here’s a heads-up. We’ll be using and referencing a lot of colors. Normally, we reference colors in Android like this:

ContextCompat.getColor(context, R.id.yourcolor);

Now I’m no fan of writing such a lengthy line for fetching a simple color resource.

So I’ll write a simple method that shortens what I have to type.

private int fetchColor(@ColorRes int color) {
        return ContextCompat.getColor(this, color);
    }

Great! From now on I don’t  have to write long lines. This simple method call will do to fetch my color resource.

TIP:
Hiding the complexities of a system by providing a simpler interface is known as the Facade Design Pattern.

With that out of the way, let’s look at implementing all the possible styling options.

Simple Theming

At the most basic level, the Bottom Navigation requires these attributes:

Android Material UI Template 8 in 1 CodeCanyon
  1. Default background color
  2. Accent color – highlights active items
  3. Inactive color – (you guessed it!) color for inactive items
bottomNavigation.setDefaultBackgroundColor(Color.WHITE);
bottomNavigation.setAccentColor(fetchColor(R.color.yourAccentColor));
bottomNavigation.setInactiveColor(fetchColor(R.color.yourInactiveColor));

With such basic styling, you can expect your Bottom Navigation to look like this.

Bottom Navigation with basic styling

Color Ripple Effects

You can take styling a step further by using a color ripple.

Yes, I’m talking about this.

Bottom Navigation with Color Ripple

The good news is that its easy to enable a colored ripple.

//  Enables color Reveal effect
bottomNavigation.setColored(true);
// Colors for selected (active) and non-selected items (in color reveal mode).
bottomNavigation.setColoredModeColors(Color.WHITE,
                fetchColor(R.color.bottomtab_item_resting));

setColoredModeColors() defines the colors for items when using color ripple.

Text Labels

Here’s what the Material Design documentation tells us. If Bottom Navigation has:

  • 3 items – display icon and text always for all items
  • 4-5 items – display text for active icon only and hide for inactive views

 



Now, you might have a good guess on what I’m going to say next.

“This is what the Material Design guidelines suggest, so let’s do just that”.

But this time I won’t. I disagree, and so should you. I’ll tell you why.

The Material Design guidelines aren’t always right

Whether you have 3 or 5 items in your Bottom Navigation, always show text labels.

By doing so, you’ll avoid the mystery meat navigation problem that plagues Material Design.

Buttons or links that don’t explain to you what they do. Instead, you have to click on them to find out – Mystery Meat Navigation.

I’m sure we’ve all been victims of this at some point at least. We click on a button assuming it to do something, only for it to do something else entirely!

So do yourselves, and your users a favor. Always, show text labels for your Bottom Navigation icons.

bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);

I did my part to give good UX. What about you?

Translucent Bottom Navigation

Translucent Bottom Navigation

First, you create an app Theme that supports translucent navigation.

...
<style name="MyTheme.TranslucentNavigation" parent="MyTheme">
       <item name="android:windowTranslucentNavigation">true</item>
</style>

Next, in your AndroidManifest.xml, apply this Theme to your Bottom Navigation Activity.

... 
<activity
            android:name=".YourActivity"
        android:theme="@style/MyTheme.TranslucentNavigation">
...

Finally, the last step is to add one simple line to YourActivity.java.

bottomNavigation.setTranslucentNavigationEnabled(true);

NOTE:
Disable Instant Run if you observe weird UI glitches. I’ve disabled mine by default.


Behaviors

The library allows on-scroll animation for the Bottom Navigation Bar. It also supports a Translucent Theme for the same.

Quick Return Animation

A View can scroll off-screen with the content and return when the user reverse scrolls. – Quick Return

Hide on scroll – Quick Return

This is a popular Animation pattern that helps maximize screen estate while scrolling. Usually the Quick Return animation pattern is used for Toolbars.

The good new is, this library allows us to enable the same for Bottom Navigation. You just have to add this simple line.

bottomNavigation.setBehaviorTranslationEnabled(true);

Translucent Navigation with Quick Return

Now you might get ambitious and want to combine both. A translucent Bottom Navigation and Quick Return pattern.

While I applaud your bravery, there’s a small hiccup in making both work together. You already might have set up a Translucent Navigation.

But once you enable Quick Return, you might notice the scroll not behaving as expected. The Toolbar might appear clipped. No amount of fitsSystemWindows will help.

Toolbar clipping with Translucent bar + quick return

That’s the hiccup I’m talking about.

But don’t worry. I’ll tell you how to fix this. Its not perfect, but it gets the job done.

All you have to do is alter your AppBarLayout. Add a View as a child to your AppBarLayout, above the Toolbar View.. This View should have a height equal to the StatusBar, which is 24dp.

<android.support.design.widget.CoordinatorLayout >
    <android.support.design.widget.AppBarLayout>

      <LinearLayout
      android:orientation="vertical">
         <View
        android:layout_width="match_parent"
           	android:layout_height="@dimen/statusBarSize" />

       	   <android.support.v7.widget.Toolbar
            	android:id="@+id/toolbar"
           	android:layout_width="match_parent"
           	android:layout_height="?attr/actionBarSize"
           	android:background="?attr/colorPrimary"/>
    </LinearLayout>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/frame"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

</android.support.design.widget.CoordinatorLayout>

TIP:
AppBarLayout is a vertical LinearLayout that determines scrolling behavior of its child Views.

 

Translucent bar with quick return

Notification Badge

This again is simple. For the sake of demonstration, I’ll show you by creating a dummy notification.

Show notification

Let’s say I want to show a notification count of 1, for the last item. We can use the library’s AHNotification class for this.

private void createFakeNotification() {
       new Handler().postDelayed(new Runnable() {
           @Override
           public void run() {
               AHNotification notification = new AHNotification.Builder()
                       .setText("1")
                       .setBackgroundColor(Color.YELLOW)
                       .setTextColor(Color.BLACK)
                       .build();
               // Adding notification to last item.

               bottomNavigation.setNotification(notification, bottomNavigation.getItemsCount() - 1);

               notificationVisible = true;
           }
       }, 1000);
   }

The Builder allows us to customize the text, its color and the background. Then, remember to set that notification to the Bottom Navigation item.

Notification Badge

Remove notification

In the above code snippet, I used a boolean notificationVisible. It tells us whether the notification badge is currently visible or not.

Flat UI Pro

A notification must be removed or dismissed once we tap the respective item. We can do this in 2 simple steps:

  1. detect the item click via OnTabSelectedListener
  2. check if notification is visible and remove it
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
         @Override
         public boolean onTabSelected(int position, boolean wasSelected) {
             
        //TODO: update Fragment here

             // remove notification badge
       int lastItemPos = bottomNavigation.getItemsCount() - 1;
             if (notificationVisible && position == lastItemPos)
                 bottomNavigation.setNotification(new AHNotification(), lastItemPos);

             return true;
         }
     });

To remove a notification, we set an EMPTY notification for that item. That is all there is to it.

Dismissing notification badge


Adding a Fragment

You can add a simple Fragment and load it into the FrameLayout like this.

getSupportFragmentManager()
             .beginTransaction()
             .add(R.id.frame, fragment, "square")
             .commit();

TIP:
You can swap out Fragments using the replace() method.

NewFragment newFragment = new NewFragment();
 getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame, newFragment, fragment.getClass().getName())
                .commit();
Updating Fragment on Bottom Navigation Item clicks

Let’s see how to update a Fragment when you click an item.

First, go to YourFragment class and create an update() method. For demonstration purposes, let’s just update the Fragment’s background color.

Hence whenever you click a Bottom Navigation item, the Fragment’s background changes color.

public void updateColor(int color) {
    recyclerView.setBackgroundColor(color);
}

A Typical Scenario

Usually, you would want to use Different Fragments for each Bottom Navigation. So whenever an item is clicked, you’d swap out the existing Fragment for the next one.

You can do this with the above-mentioned replace() method.


Where to, from here?

The Bottom Navigation is the latest pattern added to the Material Design spec. This pushes us to rethink our navigation structures.

It might be confusing at first. But I hope this post has helped you decide when to use what.

If you still find it confusing, you can always look towards popular apps. Some of that that use Bottom Navigation include Instagram, Google+ and Quora.

SOURCE CODE:
View Source Code on GitHub

Alternate Library

The Bottom Navigation Bar library by roughike is another option you can consider. Clearly its the more popular one. But this library seems to work just as fine, so there’s no cause for alarm.

So what do you think about Bottom Navigation? It is very common in iOS but I’m excited to see how you use it in Android.

How are you going to use the Bottom Bar? Let me know in the comments below.

An App developer with an eye for design. Loves to create apps with good UI/ UX that people appreciate. In his spare time, he likes to draw and paint.

Recommended Android Books to Read

Suleiman

An App developer with an eye for design. Loves to create apps with good UI/ UX that people appreciate. In his spare time, he likes to draw and paint.

You may also like...

  • Hemant Kumar

    how can i open another activity on the click of a menu item in the bottom navigation bar ? thank you

    • Hi Hemant,
      It is not recommended to open an Activity upon clicking a Bottom Navigation item. You should display a Fragment. However, if that’s what you want to achieve, then it just like how you would normally launch an Activity using Intent.

  • Libin Antony

    how to disable current item set as first tab???

    • Hi Antony,
      I have explicity set the current item to 0: bottomNavigation.setCurrentItem(0);
      Simply removing that line should disable it. However, I strongly suggest that there should be an item selected by default (indicates the home screen).

  • Tshepo Stark

    Hi, nice tutorial thanks…I have a problem though, for the life of me I cant seem to manage to style my bottom bar, its always gray and white

    • Hi Tshepo,
      How is it that you’re styling the Bottom Bar?
      You can programmatically set the Bottom Bar color using setDefaultBackgroundColor()
      Even the icons can be colored by tinting each Drawable before instantiating AHBottomNavigationItem.

      • Tshepo Stark

        thank you so much for your reply.. here are the methods I used to style my bar, it still comes out grey

        bottomNavigation.setDefaultBackgroundColor(Color.parseColor(“#FEFEFE”));
        bottomNavigation.setAccentColor(Color.parseColor(“#F63D2B”));
        bottomNavigation.setInactiveColor(Color.parseColor(“#747474”));

  • Haryantp

    i set two items in bottom bar, but i cant customize the padding . anyone can help?

    • I’m afraid the library by default, doesn’t allow you to modify padding. I believe it conforms to the metrics suggested by the Material Design guidelines.

  • kunal

    I already checked this library but what i don’t understand is how to set the scrolling behavior so that it disappears when i scroll let’s say a recycler-view. In that demo it runs great and show-hide the bottom bar based on scrolling, but i couldn’t find app:layout_behavior=”@string/appbar_scrolling_view_behavior” anywhere.

    I want to achieve that same thing but somehow i am failing to do that. One more thing can i use both AppBarLayout with toolbar and this bottom bar navigation and screen has the listview as content and based on scrolling the list i can handle the visibility of both the bars? Thanks.

  • Mohammadreza Salari

    very useful tutorial .
    i just have a question . how i can create multiple fragment and switch between those with keep parsed data(parsed data in each fragment)