Android adding a submenu to a menuItem, where is addSubMenu()?

后端 未结 8 865
情歌与酒
情歌与酒 2020-12-01 04:55

I want to add a submenu inside my OptionsMenu to a menuItem, programatically according to my parameters. I\'ve checked \"MenuItem\" in android sdk and there is no addSubMenu

相关标签:
8条回答
  • 2020-12-01 05:50

    You should consider use a ActionProvider instead.

    public class MyActionProvider extends ActionProvider {
    
        private Context mContext;
    
        public MyActionProvider(Context context) {
            super(context);
    
            mContext = context;
        }
    
        @Override
        public View onCreateActionView() {
            //LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            return null;
        }
    
        @Override
        public void onPrepareSubMenu(SubMenu subMenu) {
            super.onPrepareSubMenu(subMenu);
    
            subMenu.clear();
    
            subMenu.add("menu 1");
            subMenu.add("menu 2");
            subMenu.add("menu 3");
        }
    
        @Override
        public boolean hasSubMenu() {
            return true;
        }
    
        @Override
        public boolean onPerformDefaultAction() {
            return super.onPerformDefaultAction();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:55

    Here's a complete answer which builds on the idea of using a placeholder but uses mostly xml to add the submenu.

    If you have a menu like so called main_menu.xml:

    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="My Menu"
        android:id="@+id/my_menu_item">
        <!-- A empty SubMenu -->
        <menu></menu>
    </item>
    </menu>
    

    Create another menu sub_menu.xml which will be used in my_menu_item:

    <menu xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:title="SubMenu One"
        android:id="@+id/submenu_one" />
      <item android:title="SubMenu Two"
        android:id="@+id/submenu_two" />
      <item android:title="SubMenu Three"
        android:id="@+id/submenu_three" />
    </menu>
    

    In your onCreateOptionsMenu:

    public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate your main_menu into the menu
       getMenuInflater().inflate(R.menu.main_menu, menu);
    
       // Find the menuItem to add your SubMenu
       MenuItem myMenuItem = menu.findItem(R.id.my_menu_item);
    
       // Inflating the sub_menu menu this way, will add its menu items 
       // to the empty SubMenu you created in the xml
       getMenuInflater().inflate(R.menu.sub_menu, myMenuItem.getSubMenu());
    
    }
    

    This solution is nice since the inflater handles most of the work.

    0 讨论(0)
提交回复
热议问题