- Bottom Navigation View Android
- Prerequisites
- Adding the Bottom NavigationView
- Setting the Activity class
- Bottomnavigationview android kotlin example
- Android BottomNavigationView Example with Kotlin Tutorial
- Create Menu for Navigation Bar
- Create a bottom navigation view
- What is FragmentContainer
- Create Fragments for Each NavigationBar Items
- Switch Between Fragments
- Complete code for Android BottomNavigationView with Navigation Items
- Bottom Navigation Bar in Android
- Steps for Creating Bottom Navigation Bar
- XML
Bottom Navigation View Android
BottomNavigationView creates bottom navigation bars, making it easy to explore and switch between top-level content views with a single tap.
Bottom Navigation Bar always stays at the bottom of your application and provides navigation between the views of your application.
Prerequisites
To be able to follow this tutorial, you’ll need:
Adding the Bottom NavigationView
To use BottomNavigationView in your project, make sure you have added the design support and the Android support artifact. To add these in your project add the below dependencies in your buid.gardle file
implementation 'com.android.support:design:28.0.0'
Now add the BottomNavigationView in the activity_main.xml file. Note that the FrameLayout serve as a container for the different fragments that are placed on it whenever the BottomNavigationView menu items are clicked. Add the below code in the activity_main.xml file.
Here in the BottomNavigationView the menu items are added with bottom_menu.xml file
Add a file bottom_menu.xml in res/menu directory.
bottom_menu.xml
Setting the Activity class
Now we are going to setup NavigationView and NavigationItemSelectedListener .
package com.kotlincodes.bottomnavigationview import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.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) title=resources.getString(R.string.favorites) loadFragment(FavoriteFragment()) navigationView.setOnNavigationItemSelectedListener < when(it.itemId)< R.id.navigation_fav-> < title=resources.getString(R.string.favorites) loadFragment(FavoriteFragment()) return@setOnNavigationItemSelectedListener true >R.id.navigation_home-> < title=resources.getString(R.string.home) loadFragment(HomeFragment()) return@setOnNavigationItemSelectedListener true >R.id.navigation_settings-> < title=resources.getString(R.string.settings) loadFragment(SettingsFragment()) return@setOnNavigationItemSelectedListener true >> false > > private fun loadFragment(fragment: Fragment) < // load fragment val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() >>
Here we are not using the findViewById method to bind the views, we are just using synthetic binding extensions from Kotlin by importing the following
import kotlinx.android.synthetic.main.activity_main.*
We’ll start with the FavoriteFragment.kt class and you should follow a similar process for the remaining two fragment classes—HomeFragment.kt and SettingsFragment.kt.
The fragment added here is the basic one just uses one TextView, you can replace it with any Fragment.
FavoriteFragment.kt
package com.kotlincodes.bottomnavigationview import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class FavoriteFragment : Fragment() < override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? < return inflater.inflate(R.layout.fragment_fav,container,false) >>
fragmet_fav.xml
That’s it! Now run the project! The full source code is available here.
This is a simple app showing how to add bottom navigation view in Kotlin. – kotlincodes/BottomNavigationBar-Android-kotlin
Bottomnavigationview android kotlin example
Welcome, here we are going to implement the BottomNavigationView, which you might have seen in the Instagram application, the bottom menu bar.
Let’s start with the development:
Open Android Studio and create a new project. Setup the Constraint layout and also add the dependency of material components and syn the project.
First, create the main screen layout where we will see the bottom navigation bar and also the area above it, we are going to show three different fragments in it, so we need FrameLayout which will hold our fragments.
Just like we set menu in navigationView chapter; we also need to set here the menu which we want to show in the bar. We use the attribute
Create a menu file in the menu folder, we name the file as navigation.
Here, we have three items, and we also added the icons. This icon by default you will get in your project. Now, we need three items, so we also need three different fragment classes and one layout file for them.
We are showing the same layout in all three fragments so we will create only one layout file else to show different UI we can also create different layout files.
We will create three fragment classes.
class BlogFragment : Fragment() < override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_common, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) < super.onActivityCreated(savedInstanceState) >> class ChapterFragment : Fragment() < override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_common, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) < super.onActivityCreated(savedInstanceState) >> class StoreFragment : Fragment() < override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_common, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) < super.onActivityCreated(savedInstanceState) >>
Let’s come back to MainActivity, where we will wire up the fragments with the BottomNavigationView.
First, we need to set the toolbar as actionBar.
setSupportActionBar(toolbar)
Now, we will set the listener to the BottomNavigationView and pass the listener item to it.
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
When our application first open, we need to set one of the items already selected to show on the screen. We will check if our savedInstanceState is null we will set one the fragments.
if (savedInstanceState == null)
How to get the listener item, which we need to pass to the bottomNavigationView?
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener < menuItem ->when (menuItem.itemId) < R.id.navigation_blog -> < val fragment = BlogFragment() supportFragmentManager.beginTransaction().replace(R.id.container, fragment, fragment.javaClass.getSimpleName()) .commit() return@OnNavigationItemSelectedListener true >R.id.navigation_chapter -> < val fragment = ChapterFragment() supportFragmentManager.beginTransaction().replace(R.id.container, fragment, fragment.javaClass.getSimpleName()) .commit() return@OnNavigationItemSelectedListener true >R.id.navigation_store -> < val fragment = StoreFragment() supportFragmentManager.beginTransaction().replace(R.id.container, fragment, fragment.javaClass.getSimpleName()) .commit() return@OnNavigationItemSelectedListener true >> false >
Here, we are checking which item user will select and what action to perform on click. So, on clicking the item, we are getting the fragment instance and placing the fragment into the FrameLayout.
Let’s set some different text on every fragment and different background colors. To do this, we will change the text in onActivityCreated method in our fragment.
tvCommon.text = "Store Fragment" commonLayout.setBackgroundColor(resources.getColor(android.R.color.darker_gray)) tvCommon.text = "Chapter Fragment" commonLayout.setBackgroundColor(resources.getColor(android.R.color.holo_green_light)) tvCommon.text = "Blog Fragment" commonLayout.setBackgroundColor(resources.getColor(android.R.color.holo_orange_dark))
Let’s run this application now, Great Work!! There is much more in it like what if you want to add more items to the menu etc. Try to explore more and share us with on our twitter or slack channel.
Android BottomNavigationView Example with Kotlin Tutorial
Bottom navigation bar gives easy way for users to explore and switch between top-level views in a single tap. We can use them when when an application has three to five top-level destinations.
The bar contents can be populated by specifying a menu resource file. Each menu item contains title, icon and enabled state. This enabled state will be used for displaying bottom navigation bar items
Navigation Bar Attributes
Color of the icon when inactive
app:itemIconTint="@color/black"
Color of the text when inactive
app:itemTextColor="@color/black"
To show text labels at all times
app:labelVisibilityMode="labeled"
In this android example tutorial we are going to learn how to use BottomNavigationView in android with Kotlin Language. Let get started
1. Launch Android Studio and Create a new Android Studio project with an Empty Activity. Name the project as your wish, here i have given name as BottomNavigationView.
Choose a location on your computer where you want to save the application. If you click on the open folder you can choose a location. Now let select source language as Kotlin. Pick a minimum SDK of API 21: Android 5.0 (Lollipop). Here we no need any legacy android support libraries. Now click finish, it will create an application with default files.
Create Menu for Navigation Bar
Click on Resource Manager Tab on Left side of the Studio, if you not find this ResourceManager Tab then select it through Navigate to View->Tool Windows -> Resource Manager
Now choose Menu tabs inside Resource Manager Tab and create a Menu file. Name it as bottom_navigation_menu.xml
Add below code inside menu file
Create a bottom navigation view
Now add BottomNavigation view inside activity xml file. Add FragmentContainer to it and give an id. We will need to use it in code when switching fragments
What is FragmentContainer
FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout, so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.
FragmentContainerView should be used as the container for Fragments, commonly set in the xml layout of an activity, e.g.:
Create Fragments for Each NavigationBar Items
Let Create fragments to match each Navigation icon: HomeFragment, ExploreFragment, SubscriptionsFragment, VideoFragment.
To create a fragment right click on your package name, select
We declared BottomNavigationView inside xml file, now access it inside MainActivity.kt by using below code
val bottomNavigationView: BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView)
Handle Navigation Items click events
To receive click events for each Navigation item we need to set ItemSelected Listener to the NavigationView
bottomNavigationView.setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener < false >)
Switch Between Fragments
Now Based on selected NavigationBar item we will load respected fragment
bottomNavigationView.setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener < when(it.itemId) < R.id.navigation_home->loadFragment(HomeFragment()) R.id.navigation_explore->loadFragment(ExploreFragment()) R.id.navigation_subscriptions->loadFragment(SubScribeFragment()) R.id.navigation_library->loadFragment(VideoFragment()) > false >)
Let create loadFragment method and load respected fragment based on NavigationBar item click
To load Fragments inside the Container we will use the FragmentTransaction class.
private fun loadFragment(fragment: Fragment) < val transaction: FragmentTransaction = supportFragmentManager.beginTransaction() //this is a helper class that replaces the container with the fragment. You can replace or add fragments. //this is a helper class that replaces the container with the fragment. You can replace or add fragments. transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) //if you add fragments it will be added to the backStack. If you replace the fragment it will add only the last fra transaction.commit() >
Now run the application on device/emulator. You can switch between fragments on eaach menu item click.
Complete code for Android BottomNavigationView with Navigation Items
package com.example.bottomnavigationview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.navigation.NavigationBarView class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val bottomNavigationView: BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView) bottomNavigationView.setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener < when(it.itemId) < R.id.navigation_home-> < loadFragment(HomeFragment()) true >R.id.navigation_explore-> < loadFragment(ExploreFragment()) true >R.id.navigation_subscriptions-> < loadFragment(SubScribeFragment()) true >R.id.navigation_library-> < loadFragment(VideoFragment()) true >> false >) > private fun loadFragment(fragment: Fragment) < val transaction: FragmentTransaction = supportFragmentManager.beginTransaction() //this is a helper class that replaces the container with the fragment. You can replace or add fragments. //this is a helper class that replaces the container with the fragment. You can replace or add fragments. transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) //if you add fragments it will be added to the backStack. If you replace the fragment it will add only the last fra transaction.commit() >>
Bottom Navigation Bar in Android
We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, WhatsApp, etc. In this article, let’s learn how to implement such a functional Bottom Navigation Bar in the Android app. Below is the preview of a sample Bottom Navigation Bar:
Why do we need a Bottom Navigation Bar?
- It allows the user to switch to different activities/fragments easily.
- It makes the user aware of the different screens available in the app.
- The user is able to check which screen are they on at the moment.
The following is an anatomy diagram for the Bottom Navigation Bar:
Steps for Creating Bottom Navigation Bar
Step 1: Create a new Android Studio project
Step 2: Adding the dependency to the build.gradle(:app) file
We will be using Android’s Material Design Library so we need to import it in the build.gradle(:app) file. Here’s the dependency we need to add:
Step 3: Working with activity_main.xml file
For this example, create a basic app with a FrameLayout and a Bottom Navigation Bar. The FrameLayout will contain Fragments which will change as the user click on the items in the Bottom Navigation Bar. This is how the activity_main.xml looks like:
XML
Step 4: Creating a menu for the Bottom Navigation Bar
The Navigation Bar needs to have some items which will create using Menu. To create a Menu, first, create a Menu Directory by clicking on the app -> res(right-click) -> New -> Android Resource Directory and select Menu in the Resource Type.
To create a Menu Resource File , click on the app -> res -> menu(right-click) -> New -> Menu Resource File and name it bottom_nav_menu.
Now the user can create as many items as he wants in the bottom_nav_menu.xml file. The user also needs to create an icon for each of these items. To create an icon, click on the app -> res -> drawable(right-click) -> New -> Image Asset.
In the window that opens, the user can name the icon whatever he wants but it should not comprise any uppercase letter. The user can select the icon he wants by searching it and when the user is done, click Next-> Finish.
Now add these items in the bottom_nav_menu.xml. This is how the bottom_nav_menu.xml file looks like after adding the items: