1. Normal menu
Let's take a look at how to implement the simplest menu.
Override the oncreateoptionsmenu (menu) method in the main activity.
@ Overridepublic Boolean oncreateoptionsmenu (menu) {// todo auto-generated method stub/menu. add (0, 1, R. string. exit); // menu. add (0, 2, R. string. about); menu. add (0, 1, 1, "apple"); menu. add (0, 2, 2, "banana"); return Super. oncreateoptionsmenu (menu );}
In this way, two menu options are available. To add a click event, override the onoptionsitemselected (menuitem item) method.
@ Overridepublic Boolean onoptionsitemselected (menuitem item) {If (item. getitemid () = 1) {toast T = toast. maketext (this, "you selected Apple", toast. length_short); T. show ();} else if (item. getitemid () = 2) {toast T = toast. maketext (this, "you chose bananas", toast. length_short); T. show ();} return Super. onoptionsitemselected (item );}
Click Apple menuitem
2 submenu
Submenu creation is also simple. Add a few sentences to the oncreateoptionsmenu (menu) method of the first code, as follows:
@ Overridepublic Boolean oncreateoptionsmenu (menu) {// todo auto-generated method stub menu. add (0, 1, 1, "apple"); menu. add (0, 2, 2, "banana"); submenu = menu. addsubmenu (1,100,100, "Peach"); submenu. add (2,101,101, "Peach"); submenu. add (2,102,102, "Peach"); return Super. oncreateoptionsmenu (menu );}
After you click "Peach", the sub menu will appear. There are two sub options: "big peach" and "little peach ".