To add the Item programmatically, we can get a Menu object using getMenu()
method of NavigationView
and then we can add Items into the navigation drawer using that Menu
object.
final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 3; i++) {
menu.add("Runtime item "+ i);
}
Using SubMenu
, we can add a subsection and Items into it.
// adding a section and items into it
final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
for (int i = 1; i <= 2; i++) {
subMenu.add("SubMenu Item " + i);
}
for more details Check TechnoTalkative.
EDIT:
If you want to interact with the menu, use
menu.add(0, itemId, 0, title);
and then
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
id will give you assigned itemId
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…