Some Noob Student
Some Noob Student

Reputation: 14594

MenuItem.getItemId returns 0 instead of ItemId

I'm having problems regarding Menus and MenuItems. Whenever I click on a MenuItem, item.getItemId() always returns 0. Does anyone know why?

public class MenuAct extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.event_activity, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d("event", "ItemSelected=" + item.getItemId());// always 0
    return true;
}

}

/res/menu/event_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:name="@+id/evt_createEvent"
    android:title="1" />
<item
    android:name="@+id/menu_evt_abortCreate"
    android:title="2" />
<item
    android:name="@+id/menu_evt_saveChanges"
    android:title="3" />
<item
    android:name="@+id/menu_evt_deleteEvent"
    android:title="4" />
</menu>

Upvotes: 3

Views: 4949

Answers (2)

user1441929
user1441929

Reputation: 21

The previous answers is correct but if you are using Eclipse, perhaps is it not sufficient. Please edit your menu.xml files by using the "Layout" Editor Tab

Then your not working file

<menu xmlns:android="https://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="@string/button_exit" android:visible="true" android:enabled="true" android:id="@+id/exitmenu"></item>
</menu>

will become

<menu xmlns:android="https://schemas.android.com/apk/res/android" xmlns:android1="http://schemas.android.com/apk/res/android">
    <item android1:title="@string/button_exit" android1:visible="true" android1:enabled="true" android1:id="@+id/exitmenu"></item>

</menu>

It is probably the consequence of internal bug somewhere. So you must use the layout tab to do it otherwise you will continue to have such problem with getItemId returning zero. Now my method is returning the right id

@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {       
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.exitmenu:
                finish();//Close the app
                return true;                
        }
        return super.onMenuItemSelected(featureId, item);
    }

Upvotes: 2

Heiko Rupp
Heiko Rupp

Reputation: 30994

You are not assigning any IDs to your menu items, so Android can not know them and returns 0.

If you need the item id, you need to provide it via android:id attribute:

<item android:id="@+id/AccountStuff"
      android:title="@string/menu_switch_account"/>

Upvotes: 5

Related Questions