Steps to create a submenu in Android:
1. Overwrite the Oncreateoptionmenu () method in activity and call the menu's Addsubmenu () method to add a submenu.
2. Call the Add method of submenu, adding a submenu.
3. Overwrite the oncontextitemselected () method, and respond to the sub-menu.
Take a look at a small example:
PackageCom.yangzi.submenu;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.SubMenu; Public class mainactivity extends Activity { //Sub-menu number Private Static Final intITEM1 = Menu.first;Private Static Final intITEM2 = menu.first+1;Private Static Final intITEM3 = menu.first+3;Private Static Final intITEM4 = menu.first+4;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); }/* Overwrite Oncreateoptionmenu method, add menu, and submenu * */ @Override Public Boolean Oncreateoptionsmenu(Menu menu) {//Add menu optionssubmenu file = Menu.addsubmenu ("File"); submenu edit = Menu.addsubmenu ("Edit");//Add Sub-menu options /* * The parameter description of the Add method: * Parameter one: Group ID (int): Set ID, which indicates which group the sub-option belongs to * parameter two: item ID (int): Sub-option ID, which is used to indicate the sub-option * Parameter three: order ID (int): Display order, indicating the display order of the sub-option, default to 0, indicating in addition order * parameter four: title (String): Used to define the display text of the sub-option * * */File.add (0, ITEM1,0,"New"); File.add (0, ITEM2,0,"Open"); Edit.add (1, ITEM3,0,"Copy"); Edit.add (1,4, ITEM4,"Paste");return true; }/ * Overwrite the method and add the corresponding menu event * */ @Override Public Boolean onoptionsitemselected(MenuItem Item) {/* * Different responses based on selected sub-options (by item ID) * * The color resources used here are declared in the Color.xml file within the Res/values folder * * */ Switch(Item.getitemid ()) { CaseItem1:settitle ("New File"); Break; CaseItem2:settitle ("Open File"); Break; CaseItem3:settitle ("copy edit"); Break; CaseItem4:settitle ("Paste Edit");default: Break; }return true; }}
Try it yourself and see how it works!
Submenu in Android (submenu) use case