Responding to Menu Items Through onOptions ItemSelected

When a menu item is clicked, Android calls the onOptionsItemSelected callback method on the Activity class (see Listing 5-4).

Listing 5-4. Signature and Body of the onOptionsItemSelected Method ^Override public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()) {

//for items handled return true;

//for the rest

...return super.onOptionsItemSelected(item);

The key pattern here is to examine the menu-item ID through the getItemId() method of the MenuItem class and do what's necessary. If onOptionsItemSelected() handles a menu item, it returns true. The menu event will not be further propagated. For the menu-item callbacks that onOptionsItemSelected() doesn't deal with, onOptionsItemSelected() should call the parent method through super.onOptionsItemSelected. The default implementation of the onOptionsItemSelected() method returns false so that the "normal" processing can take place. Normal processing includes alternative means of invoking responses for a menu click.

0 0

Post a comment