Chiggins
Chiggins

Reputation: 8397

Getting menu clicks

Alright, this might be simple but I dunno how to do it! I have my menu defined through XML, as shown below. It loads and everything.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/home"
          android:title="Home" />
    <item android:id="@+id/about"
          android:title="About" />
    <item android:id="@+id/quit"
          android:title="Quit" />
</menu>

Now, going through onOptionsItemSelected(), how do I tell which menu item is selected?

This is from an example... What would the case's be?

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        Toast.makeText(this, "Home", Toast.LENGTH_LONG).show();
        return true;
    case 2:
        Toast.makeText(this, "About", Toast.LENGTH_LONG).show();
        return true;
    case 3:
        Toast.makeText(this, "Quit", Toast.LENGTH_LONG).show();
        return true;
    }
    return false;
}

Upvotes: 0

Views: 76

Answers (1)

Rich Schuler
Rich Schuler

Reputation: 41972

Your case statements should use the ids defined in your xml:

case R.id.home:
    ....
case R.id.about:
    ....
case R.id.quit:
    ....
default:
    throw new IllegalStateException("oops, forgot to code something");

the default case is just good practice imho. :)

Upvotes: 1

Related Questions