How can I add a menu dynamically to bottom navigation view?

Kiryl Belasheuski picture Kiryl Belasheuski · Dec 27, 2016 · Viewed 15.2k times · Source

Android has new ui element - BottomNavigationView

enter image description here

I don't want to contain my menus in the xml files. I will receive the information about menu items and order from backend side. I want to create them dynamically and set into the BottomNavigationView in the onCreate() method. Can I do this?

Answer

ehartwell picture ehartwell · Sep 24, 2017

By default, BottomNavigationView starts with an empty menu. You can use the getMenu() method to get the Menu instance, then add menu items as in the response above. For example,

BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);
Menu menu = bottomNavigation.getMenu();
menu.add(Menu.NONE, MENU_ITEM_ID_ONE, Menu.NONE, getString(R.string.str_menu_one))
    .setIcon(R.drawable.ic_action_one);