Creation of menu on Android

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.