Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

navigation drawer - dynamic adding item to NavigationView in Android

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: Result

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...