In the Res directory, under the menu folder, create a Main.xml file with the following contents:
<?XML version= "1.0" encoding= "Utf-8"?><Menuxmlns:android= "Http://schemas.android.com/apk/res/android"> <ItemAndroid:id= "@+id/add_item"Android:title= "Add" /> <ItemAndroid:id= "@+id/remove_item"Android:title= "Remove" /></Menu>
Note: There are two menu items created here, where the <item> tag is used to create a specific menu item, then a unique identifier is given to the menu item by Android:id and a name is given to the menu by Android:title.
Then open the activity and rewrite the Oncreateoptionsmenu () method, as follows:
// get Menuinflater object by Getmenuinflater () method Public Boolean Oncreateoptionsmenu (Menu menu ) { // calls the inflate () method to create the menus getmenuinflater (). Inflate (r.menu.main,menu); // If you return False, the created menu cannot be displayed return true ; }
Of course, it's not enough to just let the menu show up, the menu is not meant to be viewed, the key is to have the menu really available, so you need to define the menu response event.
In the activity, rewrite the onoptionsitemselected () method, which reads as follows:
Public Booleanonoptionsitemselected (MenuItem item) {//to determine the menu item by calling Item.getitemid () Switch(Item.getitemid ()) { CaseR.id.add_item:toast.maketext ( This, "You Clicked Add", Toast.length_short). Show (); Break; CaseR.id.remove_item:toast.maketext ( This, "You clicked Remove", Toast.length_short). Show (); Break; default: } return true; }
Run the program and press the menu key to display the item.
The menu is not displayed by default, and the menu is displayed at the bottom only if you press the menu key.
Original address: http://www.cnblogs.com/woider/p/5116479.html
Creation of menu on Android