Responding to Menu Item Clicks

Now that the menus are set up, we move on to step 6: responding to them. When a menu item is clicked, Android calls the onOptionsltemSelected callback method of the Activity class by passing a reference to the clicked menu item. You then use the getItemId() method on the MenuItem to see which item it is.

It is not uncommon to see either a switch statement or a series of if and else statements calling various functions in response to menu items. Listing 5-11 shows this standard pattern of responding to menu items in the onOptionsltemSelected callback method. (You will learn a slightly better way of doing the same thing in the "Loading Menus Through XML Files" section, where you will have symbolic names for these menu-item IDs.)

Listing 5-11. Responding to Menu-Item Clicks ^Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == 1) {




//hide secondary this.appendMenuItemText(item);

0 0

Post a comment