Android BottomNavigationView Using Kotlin With Example

In this article, we will learn about android BottomNavigationView using Kotlin. We will go through various example that demonstrates how to use different attributes of BottomNavigationView. For example,

In this article, we will get answer to questions like –

  • What is BottomNavigationView?
  • Why should we consider BottomNavigationView while designing ui for any app?
  • What are possibilities using BottomNavigationView while designing ui? etc.

Getting Started

We can define android BottomNavigationView widget as below –

BottomNavigationView is a standard bottom navigation bar for application. It enables user to easily navigate between top level views within application. It should be used when an application has three to five top-level destinations.

Now, how do we use BottomNavigationView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as BottomNavigationView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android BottomNavigationView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using BottomNavigationView in Kotlin

Follow steps below to use BottomNavigationView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">BottomNavigationView</string>
        <string name="home">Home</string>
        <string name="wishlist">Wishlist</string>
        <string name="profile">Profile</string>
        <string name="home_ui">Home UI Selected!</string>
        <string name="profile_ui">Profile UI Selected!</string>
        <string name="wishlist_ui">Wishlist UI selected!</string>
    </resources>
    
  • We need some drawable images for our application. You can get it by –
    1. Following article to Add Vector Image in Android Using Vector Asset Studio
    2. Following article to Add Image in Android Studio Using Image Asset Studio
    3. Downloading source code. Images can be found inside res/drawable folder.
  • We need some menus to be shown in bottom navigation bar. So, follow steps below to do it –
    1. Create new menu folder, menu, in main/res folder if not created.
    2. Create new menu xml file, bottom_menu.xml, in main/res/menu folder. Then, add below code in it –
      <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android">
          <item
              android:id="@+id/home"
              android:icon="@drawable/ic_home"
              android:title="@string/home" />
          <item
              android:id="@+id/wishlist"
              android:icon="@drawable/ic_wishlist"
              android:title="@string/wishlist" />
          <item
              android:id="@+id/profile"
              android:icon="@drawable/ic_profile"
              android:title="@string/profile" />
      </menu>
      
  • In this application, we are going to show three menus. So, we need fragment ui for each menu. each menu will have a different ui. So, follow steps below to do it –

    1. Create First Fragment (HomeFragment)

      Create new xml file, home_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              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>
      

      Now, create new Kotlin file, HomeFragment.kt, in com.tutorialwing.bottomnavigationview package. Then, add below code in it –

      package com.tutorialwing.bottomnavigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.bottomnavigationview.databinding.HomeFragmentBinding
      
      class HomeFragment : Fragment() {
      
      	private lateinit var binding: HomeFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = HomeFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.home_ui)
      	}
      }
      

      Shows only text when this fragment is shown.

    2. Create Second Fragment (ProfileFragment)

      Now, we need to create fragment for second menu i.e. profile menu. So, create new xml file, profile_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              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>
      

      Now, create new Kotlin file, ProfileFragment.kt, in com.tutorialwing.bottomnavigationview package. Then, add below code in it –

      package com.tutorialwing.bottomnavigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.bottomnavigationview.databinding.ProfileFragmentBinding
      
      class ProfileFragment : Fragment() {
      
      	private lateinit var binding: ProfileFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = ProfileFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.profile_ui)
      	}
      }
      
    3. Create Third Fragment (WishlistFragment)

      Create new xml file, wishlist_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              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>
      

      Now, create new Kotlin file, WishlistFragment.kt, in com.tutorialwing.bottomnavigationview package. Then, add below code in it –

      package com.tutorialwing.bottomnavigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.bottomnavigationview.databinding.WishlistFragmentBinding
      
      class WishlistFragment : Fragment() {
      
      	private lateinit var binding: WishlistFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = WishlistFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.wishlist_ui)
      	}
      }
      
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.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=".MainActivity">
    
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_menu" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Here,

    1. BottomNavigationView: This contains menu to be shown in bottom navigation bar of the application. Using app:menu=”” attribute, we have set menu to bottom navigation view.
    2. FrameLayout: This acts as container for view to be shown for selected menu in bottomNavigationView.
  • Now, we need to access bottomNavigationView in Kotlin file, MainActivity.kt, and perform some action on it. For example, set click listener on menu item etc. So, open Kotlin File, MainActivity.kt, and add below code in it –
    package com.tutorialwing.bottomnavigationview
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.fragment.app.Fragment
    import com.tutorialwing.bottomnavigationview.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupClickListener()
    		loadFragment(HomeFragment())
    	}
    
    	private fun setupClickListener() {
    		binding.bottomNavigationView.setOnItemSelectedListener {
    
    			val fragment = when (it.itemId) {
    				R.id.wishlist -> {
    					WishlistFragment()
    				}
    				R.id.profile -> {
    					ProfileFragment()
    				}
    				else -> {
    					HomeFragment()
    				}
    			}
    			loadFragment(fragment)
    			true
    		}
    	}
    
    	private fun loadFragment(fragment: Fragment) {
    		supportFragmentManager
    			.beginTransaction()
    			.replace(R.id.container, fragment)
    			.commit()
    	}
    }
    

    Here,

    1. onCreate(): Inside this method, we set content for main ui i.e. inflate main_activity.xml file. Then, call other methods to set click listener on bottomNavigation using Kotlin.
    2. setupClickListener(): This method sets item select listener to bottom navigation view. So, whenever any menu is selected inside bottomNavigationView, callback method is called. Inside this callback method, we match id of the selected menu and load corresponding fragment if any match is found.
    3. loadFragment(): This method takes instance of fragment as parameter and loads it into view having id container.

Now, run the application. We will get output as below –
tutorialwing kotlin android bottomnavigationview using kotlin with example

Set Custom Style to BottomNavigationView

Follow steps below to set custom style –

  1. Using style=”” attribute, we can set custom style. So, open main_activity.xml file and below code in it –
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation_view"
            style="@style/Widget.MaterialComponents.BottomNavigationView.Colored"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_menu" />
    

    Note that we have set Widget.MaterialComponents.BottomNavigationView.Colored as our custom style for bottomNavigationView. However, you can set any user defined theme using this attribute.

  2. Run application, we will get output as below –
    Tutorialwing Kotlin Android BottomNavigationView Using Kotlin Set Custom Style or theme

Show or Hide Label of Menu in BottomNavigationView

Using app:labelVisibilityMode=”” attribute, we can show or hide menu of bottomNavigationView. This accepts four values – 1. selected, 2. auto, 3. labeled or 4. unlabelled. We can choose any value as per our need.

Set Ripple Color on Selected Menu in BottomNavigationView

Whenever any menu is selected, a ripple effect is generated. If we want to set color on ripple effect, we can do so using app:itemRippleColor=”” attribute.

Create, Add or Remove Badge in BottomNavigationView

Many times we need to show count of items in any particular event in menu item. For example, number of item present in wishlist menu etc. We use Badge for such purposes. So, now we will see how to create, add or remove badge in bottomNavigationView in Kotlin.

Follow steps below to do it –

  1. We can add get or create badge using getOrCreateBadge() as below –
    binding.bottomNavigationView.getOrCreateBadge(R.id.wishlist)
    

    We can get badge of any menu as below –

    binding.bottomNavigationView.getBadge(R.id.wishlist)
    

    We can set count of item as below –

    binding.bottomNavigationView.getBadge(R.id.wishlist)?.apply {
    	number = 10
    }
    

    We can remove badge using .remove() method as below –

    binding.bottomNavigationView.removeBadge(badgeId)
    
  2. Finally, in our application, we have added some code to add badge on wishlist menu. It is removed when you click on this menu.

    So, open MainActivity.kt file and add below code in it –

    package com.tutorialwing.bottomnavigationview
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.fragment.app.Fragment
    import com.tutorialwing.bottomnavigationview.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupBottomNavigationView()
    		loadFragment(HomeFragment())
    	}
    
    	private fun setupBottomNavigationView() {
    		setupClickListener()
    		binding.bottomNavigationView.getOrCreateBadge(R.id.wishlist)
    		binding.bottomNavigationView.getBadge(R.id.wishlist)?.apply {
    			number = 10
    		}
    	}
    
    	private fun setupClickListener() {
    		binding.bottomNavigationView.setOnItemSelectedListener {
    
    			val fragment = when (it.itemId) {
    				R.id.wishlist -> {
    					removeBadge(it.itemId)
    					WishlistFragment()
    				}
    				R.id.profile -> {
    					ProfileFragment()
    				}
    				else -> {
    					HomeFragment()
    				}
    			}
    			loadFragment(fragment)
    			true
    		}
    	}
    
    	private fun removeBadge(badgeId: Int) {
    		binding.bottomNavigationView.getBadge(badgeId)?.let { badgeDrawable ->
    			if (badgeDrawable.isVisible) {
    				binding.bottomNavigationView.removeBadge(badgeId)
    			}
    		}
    	}
    
    	private fun loadFragment(fragment: Fragment) {
    		supportFragmentManager
    			.beginTransaction()
    			.replace(R.id.container, fragment)
    			.commit()
    	}
    }
    
  3. Run application, we will get output as below –
    Tutorialwing Kotlin Android Add or Remove Badge in BottomNavigationView ExampleBadge

Different Attributes of BottomNavigationView in XML

Now, we will see how to use different attributes of Android BottomNavigationView using Kotlin to customise it –

Set Id of BottomNavigationView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of BottomNavigationView using android:id attribute like below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        />

Here, we have set id of BottomNavigationView as bottomNavigationView_ID using android:id=”” attribute. So, if we need to reference this BottomNavigationView, we need to use this id – bottomNavigationView_ID.

Set Width of BottomNavigationView

We use android:layout_width=”” attribute to set width of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of BottomNavigationView

We use android:layout_height=”” attribute to set height of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of BottomNavigationView

We use android:padding=”” attribute to set padding of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in BottomNavigationView using android:padding=”” attribute.

Set Margin of BottomNavigationView

We use android:layout_margin=”” attribute to set margin of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in BottomNavigationView using android:layout_margin=”” attribute.

Set Background of BottomNavigationView

We use android:background=”” attribute to set background of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in BottomNavigationView using android:background=”” attribute.

Set Visibility of BottomNavigationView

We use android:visibility=”” attribute to set visibility of BottomNavigationView.
We can do it as below –

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of BottomNavigationView using android:visibility=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android BottomNavigationView using Kotlin. We have also gone through different attributes of BottomNavigationView to perform certain task. Let’s have a look at list of such attributes and it’s related task.

We have seen different attributes of BottomNavigationView and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is BottomNavigationView, how can we use android BottomNavigationView using Kotlin ? etc. We also went through different attributes of android BottomNavigationView.

Leave a Reply