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

后端 未结 8 892
情歌与酒
情歌与酒 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: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:

    
    
        
        
    
    
    

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

    
      
      
      
    
    

    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.

提交回复
热议问题