(Newbe)
When I click on a menu the above method returns an ID from the first menu, not the one I clicked. If I check for the Title Condensed of the menu it is correct.
int id = item.getItemId(); //returns id of an incorrect menu
String Title = (String) item.getTitleCondensed(); //this returns the correct title.
Any ideas welcome.
I had the same problem. Generated files from the build are not properly updated.
I got the same effect if i reordered the menu items in the xml...build and surprise. Clicking on menu brings other codes than expected.
Do a clean and try again
You should have set each menu item a unique ID in onCreateOptionsMenu and onCreateContextMenu.
For example:
public static final int CONTEXT_MENU_DELETE = Menu.FIRST;
public static final int CONTEXT_MENU_EDIT = CONTEXT_MENU_DELETE + 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0, CONTEXT_MENU_DELETE, 1, R.string.delete);
menu.add(0, CONTEXT_MENU_EDIT, 2, R.string.edit);
}
// And then
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case CONTEXT_MENU_DELETE:
// Delete item
break;
case CONTEXT_MENU_EDIT:
// Edit item
break;
}
}
The same is for onCreateOptionsMenu and onOptionsItemSelected. You should have a unique constant for every menu option.
Added:
Didn't you check out this tutorial?
The idea is the same. You should set different ids in menu.xml
:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game" />
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>
And then use those ids in onOptionsItemSelected
:
@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);
}
}
Check out these code blocks from official Android Menu tutorial and compare to your own code. You could also publish your menu.xml
, onCreateOptionsMenu
and onOptionsItemSelected
so it would be easy to figure out your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With