Appendj title

menu.add(0,2,1,"item2"); menu.add(0,3,2,"clear");

//It is important to return true to see the menu return true;

You should also call the base-class implementation of this method to give the system an opportunity to populate the menu with system menu items. To keep these system menu items separate from other kinds of menu items, Android adds them starting at 0x20000. (As we mentioned before, the constant Menu.CATEGORY_SYSTEM defines the starting ID for these system menu items.)

chapter 5 ■ working with menus and dialogs

The first parameter required for adding a menu item is the group ID (an integer). The second parameter is the menu-item ID, which is sent back to the callback function when that menu item is chosen. The third argument represents the sort-order ID.

The last argument is the name or title of the menu item. Instead of free text, you can use a string resource through the constants file. The group ID, menu-item ID, and sort-order ID are all optional; you can use Menu.NONE if you don't want specify any of those.

Now we'll show you how to work with menu groups. Listing 5-3 shows how you would add two groups of menus: Group 1 and Group 2.

Listing 5-3. Using Group IDs to Create Menu Groups ^Override public boolean onCreateOptionsMenu(Menu menu) {

menu.add(group1,1,1,"g1.item1"); menu.add(group1,2,2,"g1.item2");

menu.add(group2,3,3,"g2.item1"); menu.add(group2,4,4,"g2.item2");

return true; // it is important to return true

Notice how the menu-item IDs and the sort-order IDs are independent of the groups. So what good is a group, then? You can manipulate a group's menu items using these methods:


setGroupCheckable(id, checkable, exclusive) setGroupEnabled(id,boolean enabled) setGroupVisible(id,visible)

removeGroup removes all menu items from that group, given the group ID. You can enable or disable menu items in a given group using the setGroupEnabled method. Similarly, you can control the visibility of a group of menu items using setGroupVisible.

setGroupCheckable is more interesting. You can use this method to show a check mark on a menu item when that menu item is selected. When applied to a group, it will enable this functionality for all menu items within that group. If this method's exclusive flag is set, then only one menu item within that group is allowed to go into a checked state. The other menu items will remain unchecked.

Was this article helpful?

0 0

Post a comment