Intro

In this post we will demonstrate how to create a bottom navigation bar in Android using BottomNavigationView. BottomNavigationView creates bottom navigation bars, making it easy to explore and switch between top-level content views with a single tap.

You should use bottom navigation for top level destinations that need to be accessible from anywhere in the application. It is recommended that you have three to five destinations (you can’t add more than five anyway). Bottom navigation shouldn’t be used for single tasks, like viewing a single email, user preferences or settings.

The Exercise

First we are going to create a new project in Android Studio with an empty activity that we will name HomeActivity. I will name the project Bottom navigation bar exercise with Kotlin , but you can use whatever name you find suiting.  We will have to add the android material library in order to create the navigation drawer. In your app/build.gradle file add the dependency:

Next we need to create the menu items of the bottom navigation bar. In the res folder create a New Android Resource Directory:

Set the resource type to menu and press ok:

Now in the menu folder create a new Menu Resource File, i have named mine bottom_nav_menu:

Next we will create three menu items. Each item will consist of id, icon and title. The code for our menu items will look like this:

To add the icons of the menu items, you need to right click the drawable folder and select New, then Vector Asset:

Then click on the Clip art icon, to select your icon:

Select the icon that will be most suitable for your menu item:

Next, to create the bottom navigation bar, in the activity_home.xml file we will remove the automatically added TextView, and add our BottomNavigationView. The code will look like this:

 

Next we need to initialize the navigation bar in HomeActivity and configure the click events on the items to show a toast message when clicked. We will create a private fun setupNavigation() where we will create an instance of the BottomNavigationView and then use the setOnNavigationItemSelectedListener to configure the click events on the items. This method will look like this:

This is the final result:

 

 

 

You can find the whole project here: https://github.com/AleksandarGulevski/BottomNavigationBarExerciseWithKotlin

Happy coding!

 

 

 

Spread the love

3 Comments

Leave a Reply

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