text is behind BottomNavigationView
- Start by declaring and initializing a BottomNavigationView object in your Kotlin code:
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
- Next, create a Menu object to represent the menu items for the BottomNavigationView:
val menu = bottomNavigationView.menu
- Add menu items to the Menu object using the
add
method. Each menu item should have a unique identifier, a title, and an icon:
menu.add(Menu.NONE, R.id.menu_item_home, Menu.NONE, "Home").setIcon(R.drawable.ic_home)
menu.add(Menu.NONE, R.id.menu_item_search, Menu.NONE, "Search").setIcon(R.drawable.ic_search)
menu.add(Menu.NONE, R.id.menu_item_profile, Menu.NONE, "Profile").setIcon(R.drawable.ic_profile)
- Set an
OnNavigationItemSelectedListener
on the BottomNavigationView to handle item selection:
bottomNavigationView.setOnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.menu_item_home -> {
// Handle Home menu item selection
true
}
R.id.menu_item_search -> {
// Handle Search menu item selection
true
}
R.id.menu_item_profile -> {
// Handle Profile menu item selection
true
}
else -> false
}
}
- Optionally, you can set a default selected item for the BottomNavigationView using the
selectedItemId
property:
bottomNavigationView.selectedItemId = R.id.menu_item_home
- Finally, add the BottomNavigationView to your layout XML file:
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_navigation_menu" />
Make sure to replace @menu/bottom_navigation_menu
with the actual menu resource file that you created in step 3.
That's it! Your BottomNavigationView should now be set up with menu items and item selection handling.