动态添加项目NavigationView Android中 [英] dynamic adding item to NavigationView in Android

查看:2808
本文介绍了动态添加项目NavigationView Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立 NavigationDrawer 以增加新的项目(如Yahoo的天气应用程序以增加新的城市)的可能性。我有工作 NavigationDrawer NavigationView ,在菜单中我有永久的字段:

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>

我尝试添加新的项目的这个方法:

 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?

推荐答案

假设你有两个组,Group1和Group2。如果要动态地添加项目组1,那么你可以分配优先级组2使其始终低于1组。然后,当你添加新的项目组1,它不会被插入下面GROUP2。

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.

下面是一个例子:

<group android:id="@+id/group1" />
<group
    android:id="@+id/group2"
    android:orderInCategory="999">
    <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>

当你添加菜单项到组1:

And when you add menu items to group1:

Menu menu = navigationView.getMenu();
menu.add(R.id.group1,Menu.NONE,Menu.NONE,itemName);

这应该工作。我测试了它在Android设计库23.1.1。

This should work. I tested it on Android design library 23.1.1.

这篇关于动态添加项目NavigationView Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆