Android Learning Note (27): Menu

Source: Internet
Author: User

menu is made up of two forms, Option menu and Context menu. The former is press the device's menu hard button to eject, the latter is long press widget pop-up.

Option Menu

When we press the menu's Hardware button, option menu will be triggered to display up to 6 options of the icon menu, if the option is more than 6, the 6th option appears as "More", click to enter the Extended menu. We will learn option menu, which is an Activity-based menu, on the basis of the Android learning Note (11): activity-listview example.

In this example, we give an example with 7 options (excess display of up to 6 items) to set the thickness of the split line between items in the list.

Step 1: Create a menu

1.1 Set the ID of each item on the menu

private static final int eight_id = Menu.first +1;
private static final int sixteen_id = menu.first+2;
private static final int twenty_four_id = menu.first+3;
private static final int two_id = menu.first+4;
private static final int thirty_two_id = menu.first+5;
private static final int forty_id = menu.first+6;
private static final int one_id = menu.first+7;

Where Menu.first is described in reference as: first value for group and item identifier integers. We can understand the minimum value set for the ID.

1.2 Creating a Menu

When the user presses the menu key for the first time, it will trigger Oncreateoptionsmenu () and we will create our menu here

public BooleanOncreateoptionsmenu(Menu menu) {
/* The first parameter is GroupID, which can be set to Menu.none if not required. To set several menu item in the same group, you can use Setgroupvisible (), setgroupenabled (), Setgroupcheckable () method, Instead of having to do setvisible (), setenable (), setcheckable () for each item, it's easier to manage our unified management.
* The second parameter is the ID of item and we can get the specific item by Menu.finditem (ID)
* The third parameter is the order of item, generally can use Menu.none, specifically see the last part of this article Menuinflater
* The fourth parameter is the displayed content, either a string, or a reference to the Strings.xml id*/
menu.add (menu.none,one_id,menu.none, "1 Pixel");
Menu.add (Menu.none, two_id, Menu.none, "2 Pixels");
Menu.add (Menu.none, eight_id, Menu.none, "8 Pixels");
Menu.add (Menu.none, sixteen_id, Menu.none, "Pixels");
Menu.add (Menu.none, twenty_four_id, Menu.none, "Pixels");
Menu.add (Menu.none, thirty_two_id, Menu.none, "Pixels");
Menu.add (Menu.none, forty_id, Menu.none, "Pixels");
return Super.oncreateoptionsmenu (menu);
}

If we need to add icons, it is also very simple, as follows.

MenuItem item1 = menu.add (Menu.none,one_id,menu.none, "1 Pixel");
Item1.seticon (R.drawable.android_normal);

Run, press the menu key, you can get our menu, such as, the first figure is the display effect, the second figure is the effect of the more after the menu is displayed, the third figure we on the basis above, and then add three item, press more after the display effect.

Step 2:menu Trigger

The menu trigger is relatively simple, and the activity will trigger onoptionsitemselected () after the Memu is processed. As follows:

public boolean onoptionsitemselected(MenuItem item) {
... ... Join us to deal with ...
return super.onoptionsitemselected (item);
}

In this example we join the processing as follows. The image on the right shows the result of selecting 24pix.

Switch (item.Getitemid()) {//Get ID
Case ONE_ID:
Getlistview (). Setdividerheight (1);
Break
Case EIGHT_ID:
Getlistview (). Setdividerheight (8);
Break
... Similar, set the thickness of the dividing line, omit ...
Default
Break
}

Step 3: Add some changes

In the previous steps, you have learned the basic processing of option menu, but we need to add some changes

3.1 Adapt to the actual situation each time the menu is displayed

Oncreateoptionsmenu () is only triggered when the menu button is first pressed, and sometimes we want to see some changes in the menus, such as in this example, we want the menu to not show the current split height, only the height that needs to be changed, and when the split line is 16pix, The menu will not appear with item 16pix. This allows you to use Onprepareoptionsmenu (). When the user first presses the menu key, the Oncreateoptionsmenu () is executed first, then Onprepareoptionsmenu () is executed, and the user executes the Onprepareoptionsmenu when the second, third, and nth times are built by the menu. (), so we can handle each change in Onprepareoptionsmenu (). This example, the following

public BooleanOnprepareoptionsmenu(Menu menu) {
/* Set all item settings to be visually annoying, remembering the benefits of setting gourpid, can use Menu.setgroupvisible (Menu.none, True) instead. But to be reasonable, we should set our own groupid, so we still have to set each item */
Menu.finditem (one_id). setvisible (True);
Menu.finditem (eight_id). setvisible (True);
... Similar, set menu item visible, omit ...
SwitchGetlistview (). Getdividerheight (){//If the height you want to set is the same as the current height, it is not displayed.
Case 1:
Menu.finditem (one_id). setvisible (false);
Break
Case 8:
Menu.finditem (eight_id). Setchecked (True);
Break
... To be in a similar, omitted ...
Default
Break
}
return Super.onprepareoptionsmenu (menu);
}

3.2 Shortcut keys

Today's smartphones are generally straight without keyboards, but traditional phones may be T9 keyboards, or they may be full keyboards. Android support shortcut keys, although may not be used to, for the full keyboard, we can add the following code in Oncreateoptionsmenu (), so that can be triggered in both ctrl-a and alt-a.

Menu.finditem (one_id). Setalphabeticshortcut (' A ');

For the T9 keyboard, because the simulator is not T9 keyboard, there is no T9 phone, the final effect has not been tested, the following processing:

Menu.setqwertymode (TRUE);
Menu.finditem (two_id). Setnumericshortcut (' 2 ');

3.3 Set item to display the format of the checkbox

We have selected two item to set it as follows:

1) Setting these two item in Oncreateoptionsmenu () is the status of whether checked can be displayed:

Menu.finditem (eight_id). Setcheckable (True);
Menu.finditem (forty_id). setcheckable (true);

2) in Onprepareoptionsmenu (), how it will be consistent with the current state of this setting checked state, for example:

Case 8:
Menu.finditem (eight_id). setchecked (true);
Break
Case 40:
Menu.finditem (forty_id). Setchecked (True);
Break

3) when can I show

Let's look at the results of these two, we found that the "8 pix" in the case of the menu has not changed, and the choice of 40, there has been a change. Why is that? The prerequisite for display is a sufficient position to display. In the "8 pix" because it is the first page of the menu of 6 item, there is not enough position, and the 40px is more after the form of the list is displayed, there is enough position, so can be displayed.

Similarly, for the example of adding icom, we can see the icon on the first page, if the icon is displayed in more ways, the image is not visible, and Android will adapt to the UI situation.

4) We can deal with it through group:

Menu.setgroupcheckable (group_id, True, false); In this example, you can use Menu.none as a group_id to experiment

The second parameter is whether to allow checkable, and the third parameter is very interesting, true indicates that can be single-selection, using the radio button, as shown in the left-hand image, False indicates that you can select multiple, as shown in the right.

Step 4: Sub-menu

Android supports level two menus, but it does not support multilevel menus such as Level three. The submenu is set below, in Oncreateoptionsmenu (), as follows:

With the Addsubmenu Setting submenu, add menu as item. Parameters are consistent with AddMenu, for simplicity, our ID here is directly represented by a number
Submenu submenu = menu. Addsubmenu (Menu.none, Menu.none, "Sub-menu Test");
Add Item to submenu in submenu
Submenu.add (Menu.none,101,menu.none, "sub One");
Submenu.add (Menu.none,102,menu.none, "sub-");
Submenu.add (Menu.none,103,menu.none, "sub Three");
Submenu.add (Menu.none,104,menu.none, "Sub Four");

Shown below, we are added after the original menu, so we need to press more to view:

Context Menu

The Context menu is a menu that the user's finger long presses a view trigger. The process is as follows:

Step 1: Register ContextMenu for a view

For example, in our example, the entire ListView is processed in OnCreate ():

Registerforcontextmenu (Getlistview ());

Step 2: Create the ContextMenu

Create a context Menu by using the override Oncreatecontextmenu (). If we have registered Contextview for multiple view, then we can use the second parameter view V to determine what kind of menu we need to create. The third parameter contextmenuinfo is related to the specific view attribute, and if it is list, it is the item in the list, so that we can handle the menu based on the current state of the item, such as whether checked.

public void Oncreatecontextmenu (ContextMenu menu, View V, contextmenuinfo menuinfo) {
... Set menu to handle, same as option menu ...., same support sub-menu
Super.oncreatecontextmenu (menu, V, menuinfo);
}

Every time we press the widget, it triggers the processing of oncreatecontextmenu (), which is different from option menu. ContextMenu will be discard each time it is processed, so we do not keep the menu and menu item objects inside for other processing.

Step 3: Click on the menu trigger function

Trigger oncontextitemselected (). Here is only one MenuItem, so in the program, each MenuItem ID should be unique, if we need to get menuinfo, you can use Item.getmenuinfo () to obtain.

public boolean oncontextitemselected (MenuItem item) {
... What we are dealing with ...
return super.oncontextitemselected (item);
}

To define a menu through XML

In the Android learning Note (17): Again in the ListView, use Layoutinflater infalter = getlayoutinflater(); Get the layout style from the XML file. A similar approach can be used in the menu. We deal with the following in Oncreateoptionsmenu ():

public boolean Oncreateoptionsmenu (Menu menu) {
Menuinflater menuinflater = new Menuinflater (Getapplication ());
Menuinflater.inflate (R.menu.chapter11_menu, menu);
return Super.oncreateoptionsmenu (menu);
}

Where we create the menu XML file chapter11_menu.xml below the Res/menu directory. Let's look at how the menu XML file is written using the following example:

<?xml version= "1.0" encoding= "Utf-8"?>
<!--menu corresponds to a menu format--
<MenuXmlns:android= "Http://schemas.android.com/apk/res/android" >
<!--we set it in three different situations-
<!--Part 1: Normally, we add three Menuitem,item to the MenuItem format. The Android:id in item is directly the ID of item, which is the second parameter in our Menu.add (). -
<item android:id= "@+id/c11_close"
<!--title is the fourth parameter of the third parameter in the displayed text, which is menu.add (), which can be used @string/xxx--
Android:title= "Close"
<!--Orderincategory show that the order of placement, not necessarily from 0 or calculate, but must be greater than or equal to 0, the value is small in front, if the value, in our example 3 two values, then put in order, this is equivalent to Menu.add () The third parameter in the order. Of course we suggest that from 0,1,2,3 .... This is given in turn, and is consistent with the order in which the XML is worded. -
Android:orderincategory= "3"
<!--icon settings icons, not self-explanatory
Android:icon= "@drawable/android_focused"/>
<item android:id= "@+id/c11_no_icon"
Android:orderincategory = "2"
Android:title = "Sans Icon"/>
<item android:id= "@+id/c11_disabled"
android:orderincategory= "4"
Android:enabled= "false"
android:title= "Disabled"/>
<!--part 2:group, we put 2 item in group, if we want to show 3.4 way, we can increase the group parameter Android:checkablebehavior to set, single means radio Box,all indicates that Checkbox,none represents Checkable=flase. The Android:id in group is the first parameter in gourp_id, which is menu.add (). In this example, we set the group not to be seen, and if necessary, the code is: menu.setgroupvisible (R.id.c11_other_stuff, true);-->
<group android:id= "@+id/c11_other_stuff"
<!--item is set by Android:orderincategory to the order of item, in group we can set another category by Menucategory, the order of the inside and the default Category is not the side of the comparison, for example here we give 0 and 5, after displaying the default Category, and then display the content of this sendonary. -
android:menucategory= "Secondary"
Android:checkablebehavior= "single"
Android:visible= "false" >
<item android:id= "@+id/c11_later"
android:orderincategory= "0"
android:title= "2nd-to-last"/>
<item android:id= "@+id/last"
android:orderincategory= "5"
Android:title= "Last"/>
</group>
<!--Part 3: The settings of the submenu, a <menu&gt is nested inside the MenuItem, and in this example the submenu tests the shortcut key-
<item android:id= "@+id/c11_submenu"
android:orderincategory= "3"
android:title= "A submenu" >
<menu>
<item android:id= "@+id/c11_non_ghost"
Android:title= "Non-ghost"
Android:visible= "true"
Android:Alphabeticshortcut= "N"/>
<item android:id= "@+id/c11_ghost"
Android:title= "Ghost"
Android:visible= "true"
android:alphabeticshortcut= "G"/>
</menu>
</item> <!--end of Part 3--
</menu>

RELATED links: My Andriod development related articles

Android Learning Note (27): Menu

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.