How to Code a Bottom Navigation Bar for an Android App

Final product image
What You’ll Be Creating

The material design team at Google defines the functionality of bottom navigation bars in Android as follows:

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

Tapping on a bottom navigation icon takes you directly to the associated view or refreshes the currently active view.

According to the official material design guidelines for the bottom navigation bar, it should be used when your app has:

  • three to five top-level destinations
  • destinations requiring direct access

An example of a popular app that implements the bottom navigation bar is the Google+ Android app from Google, which uses it to navigate to different destinations of the app. You can see this yourself by downloading the Google+ app from Google Play store (if you don’t already have it on your device). The following screenshot is from the Google+ app displaying a bottom navigation bar. 

Screenshot of Google Android app

In this post, you’ll learn how to display menu items inside a bottom navigation bar in Android. We’ll use the BottomNavigationView API to perform the task. For an additional bonus, you’ll also learn how to use the Android Studio templates feature to quickly bootstrap your project with a bottom navigation bar. 

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

Prerequisites

To be able to follow this tutorial, you’ll need:

1. Create an Android Studio Project

Fire up Android Studio and create a new project (you can name it BottomNavigationDemo) with an empty activity called MainActivity. Make sure to also check the Include Kotlin support check box. 

Create Android Project dialog

2. Adding the BottomNavigationView

To begin using BottomNavigationView in your project, make sure you import the design support and also the Android support artifact. Add these to your module’s build.gradle file to import them. 

dependencies {
    implementation 'com.android.support:design:27.0.2'
}

Also, visit your res/layout/activlty_main.xml file to include the BottomNavigationView widget. This layout file also includes a ConstraintLayout and a FrameLayout. Note that the FrameLayout will serve as a container or placeholder for the different fragments that will be placed on it anytime a menu item is clicked in the bottom navigation bar. (We’ll get to that shortly.)  

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        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:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.chikeandroid.bottomnavigationdemo.MainActivity">

    <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigationView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:itemBackground="@color/colorPrimary"
            app:itemIconTint="@color/white"
            app:itemTextColor="@color/white"
            app:menu="@menu/navigation"/>

</android.support.constraint.ConstraintLayout>

Here we have created a BottomNavigationView widget with the id navigationView. The official documentation says that:

BottomNavigationView represents a standard bottom navigation bar for application. It is an implementation of material design bottom navigation.

Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. It should be used when application has three to five top-level destinations.

The important attributes you should take note of that were added to our BottomNavigationView are:

  • app:itemBackground: this attribute sets the background of our menu items to the given resource. In our case, we just gave it a background colour. 
  • app:itemIconTint: sets the tint which is applied to our menu items’ icons.
  • app:itemTextColor: sets the colours to use for the different states (normal, selected, focused, etc.) of the menu item text.

To include the menu items for the bottom navigation bar, we can use the attribute app:menu with a value that points to a menu resource file. 

<android.support.design.widget.BottomNavigationView
            app:menu="@menu/navigation"/>

Here is the res/menu/navigation.xml menu resource file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/navigation_songs"
            android:icon="@drawable/ic_music_note"
            android:title="Songs"/>

    <item
            android:id="@+id/navigation_albums"
            android:icon="@drawable/ic_album"
            android:title="Albums"/>

    <item
            android:id="@+id/navigation_artists"
            android:icon="@drawable/ic_person"
            android:title="Artists"/>

</menu>

Here we have defined a Menu using the <menu> which serves as a container for menu items. An <item> creates a MenuItem, which represents a single item in a menu. As you can see, each <item> has an id, an icon, and a title.

3. Initialization of Components

Next, we are going to initialize an instance of BottomNavigationView. Initialization is going to happen inside onCreate() in MainActivity.kt.

import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    lateinit var toolbar: ActionBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        toolbar = supportActionBar!!
        val bottomNavigation: BottomNavigationView = findViewById(R.id.navigationView)
    }
}

4. Testing the App

Now we can run the app!

First demo app showing bottom navigation

As you can see, our bottom navigation bar is showing at the bottom of the app screen. Nothing will happen if you click on any of the navigation items there—we’re going to handle that part in the next section. 

5. Configuring Click Events

Now, let’s see how to configure click events for each of the items in the bottom navigation bar. Remember that clicking on any item in there should take the user to a new destination in the app.

// ...
    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_songs -> {
                
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_albums -> {
             
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_artists -> {
                
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        // ... 
        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }
// ...     

Here we called the method setOnNavigationItemSelectedListener. Here is what it does according to the official documentation:

Set a listener that will be notified when a bottom navigation item is selected.

We used the when expression to perform different actions based on the menu item that was clicked—the menu item ids serve as constants for the when expression. At the end of each when branch, we return true.

We then pass our mOnNavigationItemSelectedListener listener to setOnNavigationItemSelectedListener() as an argument. 

Be aware that there is another similar method called setOnNavigationItemReselectedListener, which will be notified when the currently selected bottom navigation item is reselected.

Next, we are going to create the different pages (or Fragments) for each of the menu items in the navigation drawer so that when a menu item is clicked or tapped, it displays a different Android Fragment or page. 

6. Creating the Fragments (Pages)

We’ll start with the SongsFragment.kt class, and you should follow a similar process for the remaining two fragment classes—AlbumsFragment.kt and ArtistsFragment.kt.

Here is my SongsFragment.kt:

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class SongsFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater.inflate(R.layout.fragment_songs, container, false)

    companion object {
        fun newInstance(): SongsFragment = SongsFragment()
    }
}

Also, here is my R.layout.fragment_songs

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Songs"
            android:gravity="center_vertical|center_horizontal"/>

</LinearLayout>

7. Launching the Fragments

When any of the menu items is clicked, we open the corresponding Fragment and also change the action bar title. 

private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.navigation_songs -> {
            toolbar.title = "Songs"
            val songsFragment = SongsFragment.newInstance()
            openFragment(songsFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_albums -> {
            toolbar.title = "Albums"
            val albumsFragment = AlbumsFragment.newInstance()
            openFragment(albumsFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_artists -> {
            toolbar.title = "Artists"
            val artistsFragment = ArtistsFragment.newInstance()
            openFragment(artistsFragment)
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

private fun openFragment(fragment: Fragment) {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.container, fragment)
    transaction.addToBackStack(null)
    transaction.commit()
}

Here we’re using a method called openFragment() that simply uses the FragmentTransaction to add our fragment to the UI. 

Now run the project again to see how it all works!

Final app demo with click events

Anytime you click on any menu item, it will take the user to a new Fragment. 

Note that when we have more than four menu items in the bottom navigation bar—i.e. in BottomNavigationView—then the Android system automatically enables shift mode. In this mode, when any of the menu items is clicked, the other items on the right or left of the clicked item are shifted. 

BottomNavigationView with shift mode

8. Bonus: Using Android Studio Templates

Now that you have learnt about the APIs involved to create a bottom navigation bar from scratch in Android, I’ll show you a shortcut that will make it faster next time. You can simply use a template instead of coding a navigation bar from scratch. 

Android Studio provides code templates that follow the Android design and development best practices. These existing code templates (available in Java and Kotlin) can help you quickly kick-start your project. One such template can be used to create a bottom navigation bar. 

To use this handy feature for a new project, first fire up Android Studio. 

Create Android Project dialog

Enter the application name and click the Next button. You can leave the defaults as they are in the Target Android Devices dialog. 

Click the Next button again. 

Add an Activity to Mobile dialog

In the Add an Activity to Mobile dialog, select Bottom Navigation Activity. Click the Next button again after that. 

Configure Activity dialog

In the last dialog, you can rename the Activity, or change its layout name or title if you want. Finally, click the Finish button to accept all configurations. 

Android Studio has now helped us to create a project with a bottom navigation activity. Really cool!

You are strongly advised to explore the code generated. 

In an existing Android Studio project, to use this template, simply go to File > New > Activity > Bottom Navigation Activity.

Navigation from file menu to Bottom Navigation Activity

Note that the templates that come included with Android Studio are good for simple layouts and making basic apps, but if you want to really kick-start your app, you might consider some of the app templates available from Envato Market

They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

Conclusion

In this tutorial, you learned how to create a bottom navigation bar in Android using the BottomNavigationView API from scratch. We also explored how to easily and quickly use the Android Studio templates to create a bottom navigation activity. 

I highly recommend checking out the official material design guidelines for bottom navigation bar to learn more about how to properly design and use the bottom navigation bar in Android.   

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

Leave a Reply

Your email address will not be published. Required fields are marked *