The menu is a very important part of the mobile app, it allows users to choose from an intuitive interface, and now we learn how to create a new menu.
First create a new menu folder under the Res directory, and then create a new Android XML file under the menu folder and name it main. And then in
Add the following code to the Main.xml:
<?XML version= "1.0" encoding= "Utf-8"?><Menuxmlns:android= "Http://schemas.android.com/apk/res/android" > < Item android:id= "@+id/add_item" Android:title = "@string/app_add" />< Item android:id= "@+id/remove_item" Android:title = "@string/app_remove" /> </Menu>
tags in the code <item> are used to create a specific menu item, and then through the
Android:id Specify a unique identifier for the menu item;
Android:title Specify a name for this menu item.
After creating the menu file, you need to override the Oncreateoptionsmenu () method in Firstactivity, with the following code:
// overriding the Oncreateoptionsmenu () method, adding a menu Public Boolean Oncreateoptionsmenu (Menu menu) { getmenuinflater (). Inflate (R.menu.main, menu); return true ; }
where the Getmenuinflater () method can get the Menuinflater object, the inflate () method that calls it can create a menu for the current activity.
The inflate () method receives two parameters,
The first one: to specify which resource file we use to create the menu, the R.menu.main menu file is passed in;
The second one: Used to specify which menu object our item will be added to, and use the menu parameter passed in directly in the Oncreateoptionsmenu () method.
The overridden method returns True, indicating that the menu created is allowed to be displayed, and if False, the created menu cannot be displayed.
The above method is just to let the menu show, we also need to rewrite the onoptionsitemselected () method to use the menu, the following code is used to define the menu response event:
//defining Menu Response events, overriding the Onoptionsitemselected () method Public Booleanonoptionsitemselected (MenuItem item) {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; }
In the Onoptionsitemselected () method, by calling Item.getitemid () to determine which menu item we clicked on, we can then add our own logic processing to each menu item. We are here to join toast.
Rerun the program, the menu is not displayed by default, click the Menu key, you can get the effect:
Android Learning Notes (iii)