I prepared 2 xml menu files and placed inside my res/menu folder.
menu_beforeLogin.xml will be displayed if the user didn't logged in. After they logged in, the menu item will changed to menu_afterLogin.xml.
I tried to called InflateMenu() in my onResume() method, but it ends up with keep adding the items from xml file whenever onResume() is invoked instead of removing/regenerate the menu list.
I would prefer to check user is logged in or not in onResume() method.
What is the proper way to change Navigation Drawer's list dynamically ?
MainActivity.cs
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
...
mDrawer = FindViewById<NavigationView>(Resource.Id.navigation_drawer);
...
}
protected override void OnResume ()
{
base.OnResume ();
string token = pref.GetString (Constant.PREF_TOKEN, "");
mDrawer.InflateMenu ( (token == "") ? Resource.Menu.menu_drawer_notLoggedIn : Resource.Menu.menu_drawer);
mDrawer.Invalidate ();
...
}
layout/main.axml
<android.support.v4.widget.DrawerLayout>
<android.support.design.widget.CoordinatorLayout>
...
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@drawable/menu_background"
app:headerLayout="@layout/drawer_header" />
</android.support.v4.widget.DrawerLayout>
res/menu/menu_beforeLogin.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_login"
android:icon="@drawable/navigation_login"
android:title="@string/navigation_login" />
<item
android:id="@+id/navigation_notice"
android:icon="@drawable/navigation_notice"
android:title="@string/navigation_notice" />
<item
android:id="@+id/navigation_contactUs"
android:icon="@drawable/navigation_contactUs"
android:title="@string/navigation_contactUs" />
</menu>
res/menu/menu_afterLogin.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_notice"
android:icon="@drawable/navigation_notice"
android:title="@string/navigation_notice" />
<item
android:id="@+id/navigation_profile"
android:icon="@drawable/navigation_profile"
android:title="@string/navigation_profile" />
<item
android:id="@+id/navigation_contactUs"
android:icon="@drawable/navigation_contactUs"
android:title="@string/navigation_contactUs" />
<item
android:id="@+id/navigation_logout"
android:icon="@drawable/navigation_logout"
android:title="@string/navigation_logout" />
</menu>
Add this method to clear your menu item before inflating new menu.
mDrawer.Menu.Clear ();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments