This example shows how to expand a menu item from the menus resource (XML definition). The oncreate of this example employs the method of using code to create an activity interface, and the usual approach is to use layout resources. If you are interested in understanding how to create a UI using code, you can refer to the OnCreate method of this example, but that is not the purpose of this example.
The general step in using an XML menu resource to expand a menu is
1. In the/res/menu directory to define menu resources, this example defines 10 different styles of food items: "Title only", "title and Icon", "submenu", "Groups", "checkable", "shortcuts", ' Order ', ' Category and Order ', ' Visible ', ' Disabled '.
The simplest menu resource is defined as follows: Only the ID and title definitions are included.
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >
<item android:id= "@+id/jump"
android:title= "@string/jump"/>
<item android:id= "@+id/centere"
android:title= "@string/centere"/>
</menu>
2. Expand Menu Resources, Android supports two categories of menu option (Main menu), context menu (context-sensitive menu). This example uses option menu to expand the menu resource using Menuinflater in the public boolean Oncreateoptionsmenu (menu) method:
@Override Public
Boolean oncreateoptionsmenu (Menu menu) {
//Hold on to this
mmenu = menu;
Inflate the currently selected menu XML resource.
Menuinflater inflater = Getmenuinflater ();
Inflater.inflate
(Smenuexampleresources[mspinner.getselecteditemposition ()],
menu);
Disable the spinner since we ' ve already created the menu and the user
/can no longer pick a different menu xml.< C11/>mspinner.setenabled (false);
Change Instructions
minstructionstext.settext (getresources (). getString (
R.string.menu_from_xml_ Instructions_go_back));
return true;
}
3. Add a method to handle the event for the menu.
@Override Public
Boolean onoptionsitemselected (MenuItem item) {
switch (Item.getitemid ()) {
case R.id.jump: ...
Default:
..
However, when a user selects a menu, the Onoptionsitemselected event is triggered, and the parameter item is the menu item selected by the user, which can be used to implement the corresponding action of the item according to its ID.
This example menu uses 10 different styles, the basic usage is the same, different is defined in the XML Item property.
Title only
The simplest menu, the menu contains only text descriptions.