简体   繁体   中英

Xamarin.Android : Add the dynamic menu items to Navigation view of DrawerLayout

I followed this sample to design the Navigation menu view using android.support.v4.widget.DrawerLayout.

My Static Menu item list defined in drawer_menuList.xml as :

 <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/item1"
            android:icon="@drawable/item1"
            android:title="Item1" />
        <item
            android:id="@+id/Item2"
            android:icon="@drawable/item2"
            android:title="Item2"/>
    </group>

activity_main.axml :

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menuList" />

I found this similar thread on stack overflow and tried this :

NavigationView mDrawerList = FindViewById<NavigationView>(Resource.Id.nav_view);

Menu menu = mDrawerList.getMenu();

I am not getting any getMenu() / GetMenu() method in xamarin.android. Can anyone suggest the right way to add the menu along with the icons dynamically in NavigationView of DrawerLayout.

Answering to my question :

Suppose you have a list of Menu items such as :

List<MenuItems> lst = new List<MenuItems>();
lst = GetMenuItems();

Then in xamarin we can dynamically populate the Menu items with their title and icon as :

NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
    foreach (MenuItems objMenuItems in lst)
      {
         int iconID = (int)typeof(Resource.Drawable).GetField(objMenuItems.IconName).GetValue(null);

         navigationView.Menu.Add(objMenuItems.Title).SetIcon(iconID);
      } 

By this way you can dynamically add the menu items in NavigationView of DrawerLayout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM