Android BottomNavigationView Example in Kotlin

This article is about Android BottomNavigationView (represents a standard bottom navigation bar for application) and how to combine it with Fragments with the help of a simple application.

BottomNavigationView

  • BottomNavigationView makes it easy for users to explore and switch between top-level views in a single tap.
  • It should be used when the app has three to five top-level navigations.
  • When there are two top-level destinations then use Tabs but If Destinations are more than five then use the Navigation Drawer.
  • Bottom navigation should be used for Top-level destinations that need to be accessible from anywhere in the app.
  • When the user taps on the icon it will change the top-level view accordingly.

The following is an example of the Bottom Navigation bar:

Creating new project

1 . Create a new project by going to File  New Android Project, select Empty Activity, provide app name, select language to kotlin and then finally click on finish.

2 . Open app-level build.gradle file, add the dependency of material design in the dependencies section, and sync the project.

build.gradle

dependencies {
    //material design
    implementation 'com.google.android.material:material:1.5.0-alpha01'
}

Find the latest version of the material design from here.

3 . As the Bottom Navigation items are rendered using a menu file, create a new xml file named bottom_navigation_menu.xml under res ⇒ menu folder.

bottom_navigation_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_home"
        android:title="Home"
        android:enabled="true"
        android:icon="@drawable/ic_home"/>
    <item
        android:id="@+id/nav_search"
        android:title="Search"
        android:enabled="true"
        android:icon="@drawable/ic_search"/>
    <item
        android:id="@+id/nav_radio"
        android:title="Radio"
        android:enabled="true"
        android:icon="@drawable/ic_radio"/>
    <item
        android:id="@+id/nav_my_music"
        android:title="My Music"
        android:enabled="true"
        android:icon="@drawable/ic_music"/>
    <item
        android:id="@+id/nav_library"
        android:title="Library"
        android:enabled="true"
        android:icon="@drawable/ic_library"/>
</menu>

4 . Create a new Fragment (named HomeFragment.kt) for the home menu item by going to root ⇒ New ⇒ Fragment ⇒ Fragment (Blank).

HomeFragment.kt

package com.c1ctech.androidbottomnavviewexp

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    companion object {
        fun newInstance() = HomeFragment()
    }
}

5 . Open fragment_home.xml and add the below TextView.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

6 . Similarly, create fragments and their layout for the other four menu Items also.

7 . Open the layout file of the MainActivity i.e activity_main.xml, add BottomNavigationView widget and also add a FrameLayout to load the Fragments when the navigation item is selected.

activity_main.xml

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

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation"
        />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:menu="@menu/bottom_navigation_menu"
        android:background="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"/>

</RelativeLayout>
  • app:menu : The menu resource file to display the navigation items along with icon and text.
  • app:itemBackground : Applies background color to bottom navigation.
  • app:itemTextColor: The text color of bottom navigation item.
  • app:itemIconTint : The icon color of bottom navigation item.

The labelVisibilityMode attribute can be used to adjust the behavior of the text labels for each navigation item.

There are four visibility modes:

  • LABEL_VISIBILITY_AUTO (default): The label behaves as “labeled” when there are 3 items or less, or “selected” when there are 4 items or more
  • LABEL_VISIBILITY_SELECTED: The label is only shown on the selected navigation item
  • LABEL_VISIBILITY_LABELED: The label is shown on all navigation items
  • LABEL_VISIBILITY_UNLABELED: The label is hidden for all navigation items

8 . Open MainActivity.kt and add the below code:

MainActivity.kt

package com.c1ctech.androidbottomnavviewexp

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        val toolbar = getSupportActionBar();

        loadFragment(HomeFragment.newInstance())

        bottom_navigation.setOnItemSelectedListener { item ->
            var fragment: Fragment
            when (item.itemId) {
                R.id.nav_home -> {
                    toolbar?.setTitle("Home")
                    fragment = HomeFragment()
                    loadFragment(fragment)
                    true
                }
                R.id.nav_radio -> {
                    toolbar?.setTitle("Radio")
                    fragment = RadioFragment()
                    loadFragment(fragment)
                    true

                }
                R.id.nav_search -> {
                    toolbar?.setTitle("Search")
                    fragment = SearchFragment()
                    loadFragment(fragment)
                    true

                }
                R.id.nav_my_music -> {
                    toolbar?.setTitle("My Music")
                    fragment = MyMusicFragment()
                    loadFragment(fragment)
                    true

                }
                R.id.nav_library -> {
                    toolbar?.setTitle("Library")
                    fragment = LibraryFragment()
                    loadFragment(fragment)
                    true

                }
                else -> false
            }

        }

        bottom_navigation.setOnItemReselectedListener { item ->
            when (item.itemId) {
                R.id.nav_home -> {
                    Toast.makeText(this, "Home Item reselected", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_radio -> {
                    Toast.makeText(this, "Radio Item reselected", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_search -> {
                    Toast.makeText(this, "Search Item reselected", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_my_music -> {
                    Toast.makeText(this, "My Music Item reselected", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_library -> {
                    Toast.makeText(this, "Library Item reselected", Toast.LENGTH_SHORT).show()

                }
            }
        }
    }

    private fun loadFragment(fragment: Fragment) {
        // load fragment
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }
}
  •  loadFragment() – loads the Fragment into FrameLayout. It is also called in OnItemSelectedListener callback by passing the appropriate fragment instance.
  • OnItemSelectedListener: listener that will be notified when a navigation item is selected.
  • OnItemReselectedListener: listener that will be notified when the currently selected navigation item is reselected.

9 . Now if you run the project you can see the fragments loaded when navigation is selected.

       

Leave a Reply