Question

I'm practising adding menu items and trying to react to menu item clicks. According to the developer's guide, it says:

Tip: Android 3.0 adds the ability for you to define the on-click behavior for a menu item in XML, using the android:onClick attribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItem parameter—when the system calls this method, it passes the menu item selected. For more information and an example, see the Menu Resource document.

However, the sample code in the same page doesn't follow the rule: the methods do not pass the MenuItem parameter. The sample code is:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

My question is: Shouldn't method calls be newGame(MenuItem item) and showHelp(MenuItem item), instead of newGame() and showHelp()? When I tested my own, (MenuItem item) argument was needed in fact, otherwise, the app was crashing, even though it compiles correctly.

Any help would be appreciated.

Was it helpful?

Solution

onOptionsItemSelected is the alternative to defining onClick attributes and what is available prior to Android 3.0 (important if you want to be backward compatible). It is simply a different way of providing the same process flow. Of course, onClick has the potential to crash your application on runtime, rather than onOptionsItemSelected not handling a menu item (simply causing it to do nothing).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top