I want to build NavigationDrawer
with the possibility of adding new items (such as yahoo weather App with adding new cities). I have working NavigationDrawer
with NavigationView
, in menu I have permanent fields:
<group
android:id="@+id/group"
android:checkableBehavior="single">
<item
android:checked="false"
android:id="@+id/item1"
android:icon="@drawable/ic_inbox_black_24dp"
android:title="Item1" />
<item
android:checked="false"
android:id="@+id/Item2"
android:icon="@drawable/ic_inbox_black_24dp"
android:title="Item2"
/>
</group>
I'm trying to add new Item this method:
public boolean addNewItem(String itemName){
Menu menu = navigationView.getMenu();
menu.add(R.id.group,Menu.NONE,Menu.NONE,itemName);
return true;
}
And I'm getting not exactly what I want:
Does anyone have an idea how to solve this problem? Or why is this happening? I do not know where and how one can hold information about the added elements. Any ideas?
Suppose you have two groups, group1 and group2. If you want to dynamically add items to group1, then you can assign priority to group2 to make it always below group1. Then when you add new items to group1, it won't be inserted below group2.
Here is a sample:
And when you add menu items to group1:
This should work. I tested it on Android design library 23.1.1.
To add the Item programmatically, we can get a Menu object using
getMenu()
method ofNavigationView
and then we can add Items into the navigation drawer using thatMenu
object.Using
SubMenu
, we can add a subsection and Items into it.for more details Check TechnoTalkative.
EDIT: If you want to interact with the menu, use
menu.add(0, itemId, 0, title);
and thenid will give you assigned itemId