Change NavigationView items when user is logged
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" />
then
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>
and
navigationView.getMenu().setGroupVisible(R.id.group_1, true)
Simple solution:
Add two xml files in menu directory:
-
navigation_with_login.xml
Navigation Menu for logged in users<?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/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_login" android:icon="@drawable/ic_menu_login" android:title="Login" /> </group> </menu>
-
navigation_with_logout.xml
Navigation Menu for default user:<?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/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_logout" android:icon="@drawable/ic_menu_logout" android:title="Logout" /> </group> </menu>
Now you can change NavigationView
items,just write few lines of code.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if(islogin)
{
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.navigation_with_login);
} else
{
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.navigation_with_logout);
}
Frst get the navigationmenu
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
To add the menu dynamically
if(loggedOut){
menu.add(R.id.submenu_others, R.id.action_logout, Menu.NONE, "logout");
}
Here is menu.add(groupId, menuItemId, orderOfMenu, menuItem text)
if(loggedIn){
menu.removeItem(R.id.action_logout);
}
I got it done, try this when you need to change the title:
navigationView.getMenu().findItem(R.id.yourItemId).setTitle("my title");
Hope it helped!