Responding to XMLBased Menu Items

You haven't yet seen the specific advantage of this approach—it becomes apparent when you start responding to the menu items. You respond to XML menu items the way you respond to menus created programmatically, but with a small difference. As before, you handle the menu items in the onOptionsItemSelected callback method. But this time, you will have some help from Android's resources (see Chapter 3 for details on resources). As we mentioned in the section "Structure of an XML Menu Resource File," Android not only generates a resource ID for the XML file, but also generates the necessary menu-item IDs to help you distinguish between the menu items. This is an advantage in terms of responding to the menu items because you don't have to explicitly create and manage their menu-item IDs.

To further elaborate on this, in the case of XML menus you don't have to define constants for these IDs and you don't have to worry about their uniqueness because resource ID generation takes care of that. The following code illustrates this:

private void onOptionsItemSelected (MenuItem item) {

this.appendMenuItemText(item);

this.emptyText();

IntentsUtils.invokePick(this);

else if (item.getItemId() == R.id.menu_testGetContent) {

IntentsUtils.invokeGetContent(this);

else if (item.getItemId() == R.id.menu_show_browser) {

IntentsUtils.tryOneOfThese(this);

Notice how the menu-item names from the XML menu resource file have automatically generated menu-item IDs in the R. id space.

0 0

Post a comment