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");
but it doesn't sound that good to me, I'm pretty sure there must be a cleaner way.
...but does it?
I thing the best approach to this is to include all your items in the menu and the change their visibility.
then
You can also do this with whole groups of items
and
Simple solution:
Add two xml files in menu directory:
navigation_with_login.xml
Navigation Menu for logged in usersnavigation_with_logout.xml
Navigation Menu for default user:Now you can change
NavigationView
items,just write few lines of code.I got it done, try this when you need to change the title:
Hope it helped!
Frst get the navigationmenu
To add the menu dynamically