How to programmatically add a submenu item to the

2019-01-06 10:46发布

I am trying to add new menu items to a submenu in the new Material Design drawer panel.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

...

    <android.support.design.widget.NavigationView
        android:id="@+id/main_navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/channel_list_header"
        app:menu="@menu/menu_nav" /> 

</android.support.v4.widget.DrawerLayout>

I do have the @menu/menu_nav setup but now want to add new menu items:

NavigationView mDrawerList = (NavigationView) findViewById(R.id.main_navigation);

Menu menu = mDrawerList.getMenu();
Menu topChannelMenu = menu.addSubMenu("Top Channels");

topChannelMenu.add("Foo");
topChannelMenu.add("Bar");
topChannelMenu.add("Baz");

mDrawerList.invalidate(); // Trying to force a redraw, doesn't help.

The menu items from the @menu/menu_nav file are shown, but the newly added ones aren't. Any ideas how to do that?

5条回答
Root(大扎)
2楼-- · 2019-01-06 11:04

This is how I manipulate the sub-menu item in NavigationView

1) Create menu.xml file

<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <group android:checkableBehavior="single">
    <item android:title="Index:" android:id="@+id/mnugrp_Index">
      <menu>

        <!--This line below is dump line for rendering dynamic sub-menu item-->
        <item android:icon="@drawable/ic_action_content_create" android:title="Sub item 1" />

      </menu>
    </item>
  </group>

  <group android:id="@+id/mnugrp_Attachment" android:checkableBehavior="single">
    <item android:title="Attachment:" android:id="@+id/mnugrp_Attachment">
    <menu>
            
      <!--This line below is dump line for rendering dynamic sub-menu item-->
      <item android:icon="@drawable/ic_action_content_create" android:title="Sub item 1" />
    
    </menu>
  </item>
  </group>  
</menu>

2) Manipulate the menu by calling this function

        /// <summary>
    /// 
    /// </summary>
    /// <param name="navView"></param>
    private void AddNavigationMenuItem (NavigationView navView)
    {
        navView.Menu.FindItem(Resource.Id.mnugrp_Index).SubMenu.Clear();
        navView.Menu.FindItem(Resource.Id.mnugrp_Index).SubMenu.Add("This is Index 1");
        navView.Menu.FindItem(Resource.Id.mnugrp_Index).SubMenu.Add("This is Index 2");
        navView.Menu.FindItem(Resource.Id.mnugrp_Index).SubMenu.Add("This is Index 3");
        navView.Menu.FindItem(Resource.Id.mnugrp_Index).SubMenu.Add("This is Index 4");

        navView.Menu.FindItem(Resource.Id.mnugrp_Attachment).SubMenu.Clear();
        navView.Menu.FindItem(Resource.Id.mnugrp_Attachment).SubMenu.Add("This is Attachment 1");
        navView.Menu.FindItem(Resource.Id.mnugrp_Attachment).SubMenu.Add("This is Attachment 2");
        navView.Menu.FindItem(Resource.Id.mnugrp_Attachment).SubMenu.Add("This is Attachment 3");
        navView.Menu.FindItem(Resource.Id.mnugrp_Attachment).SubMenu.Add("This is Attachment 4");
    }

enter image description here

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-06 11:06

[Update 20-03-2016] Bug is resolved. So no need to worry.

[This below contetnt is outdated.]

Adding a dynamic menu to NavigationView is currently bug on Design Support library. And I have report it to android bug source tracking. So wait till the bug will fixed. But if you want the temporary solution you can do it. First add your dynamic menu ..

    navView = (NavigationView) findViewById(R.id.navView);
    Menu m = navView.getMenu();
    SubMenu topChannelMenu = m.addSubMenu("Top Channels");
    topChannelMenu.add("Foo");
    topChannelMenu.add("Bar");
    topChannelMenu.add("Baz");

After adding your menu just write below code ..

    MenuItem mi = m.getItem(m.size()-1);
    mi.setTitle(mi.getTitle());

It's currently hacky solution. But work for me ...

[update 26-06-2015]

As I have reported this bug at Android Bug source Now Bug is marked as a future release, here is the link https://code.google.com/p/android/issues/detail?id=176300

So we can say that the bug is no more exist on future library. So you don't have to use tricky solution. i will also update this answer again when Future version release number is maintion for this bug.

查看更多
聊天终结者
4楼-- · 2019-01-06 11:14

I found easier way to change navigation view ( work with both submenu and menu). You can re-inflate NavigationViewat runtime with 2 lines of code. In this example, I re-inflate new_navigation_drawer_items.xml using public method inflateMenu (You can create a menu xml file with your new submenu)

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.new_navigation_drawer_items); //inflate new items.
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-06 11:28

You can add and remove item from navigation view by changing the visibility. Get the item at index and setVisible to true to show and false to hide it.

MenuItem item = navigationView.getMenu().getItem(3);
item.setVisible(false);
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-06 11:28

Use this method to add menu and submenu

private void addItemsRunTime(NavigationView navigationView) {

        //adding items run time
        final Menu menu = navigationView.getMenu();
        for (int i = 1; i <= 3; i++) {
            menu.add("Runtime item "+ i);
        }

        // adding a section and items into it
        final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
        for (int i = 1; i <= 2; i++) {
            subMenu.add("SubMenu Item " + i);
        }

        // refreshing navigation drawer adapter
        for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
            final View child = mNavigationView.getChildAt(i);
            if (child != null && child instanceof ListView) {
                final ListView menuView = (ListView) child;
                final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
                final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
                wrapped.notifyDataSetChanged();
            }
        }
    }

and call this method where you setup Drawer Content.

查看更多
登录 后发表回答