My app's main activity has a navigation drawer, instantiated in the XML in this way:
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/application_drawer"
android:background="@color/white"/>
现在,为抽屉式导航菜单项如下:
Now, the menu entry for the navigation drawer is the following:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/login"
android:icon="@drawable/ic_action_person"
android:title="@string/login"/>
<item
android:id="@+id/settings"
android:icon="@drawable/ic_action_settings"
android:title="@string/settings"/>
<item
android:id="@+id/terms"
android:icon="@drawable/ic_action_about"
android:title="@string/terms_and_conditions_menu"/>
<item
android:id="@+id/about"
android:icon="@drawable/ic_action_about"
android:title="@string/info_hotelsclick"/>
</group>
我想要做的是改变的第一个项目(也可能是其他人也)动态地在一定的条件。举例来说,我想改变登录进入了注销一,一旦用户登录; - )
What I'd like to do is to change the first item (and possibly the others as well) dynamically under some conditions. For instance, I'd like to change the "Login" entry with a "logout" one once the user has logged in ;-)
我怎样才能做到这一点?我设法加入这样一个项目的抽屉
How can I achieve that? I managed to add an item to the Drawer in this way
Menu menu = navigationView.getMenu();
menu.add("Test");
但它听起来并不对我好,我是pretty的肯定必须有一个更清洁的方式。
but it doesn't sound that good to me, I'm pretty sure there must be a cleaner way.
...但不是吗?
推荐答案
我的事情这一点的最好办法是包括你的菜单中的所有项目和改变自己的知名度。
I thing the best approach to this is to include all your items in the menu and the change their visibility.
<item
android:id="@+id/login"
android:icon="@drawable/ic_action_person"
android:title="@string/login"
android:visible="true" />
<item
android:id="@+id/logout"
android:icon="@drawable/ic_action_person"
android:title="@string/logout"
android:visible="false" />
然后
navigationView.getMenu().findItem(R.id.login).setVisible(false);
navigationView.getMenu().findItem(R.id.logout).setVisible(true);
您也可以做到这与项目的整体组
You can also do this with whole groups of items
<group
android:id="@+id/group_1"
android:checkableBehavior="single"
android:visible="false">
...
</group>
和
navigationView.getMenu().setGroupVisible(R.id.group_1, true)
相关推荐
最新文章