OnOptionsItem Selected Return Invalid Identifier

(Newbe)

When I click on a menu, the above method returns the identifier from the first menu, not the one I pressed. If I check that the name Condensed from the menu is correct.

int id = item.getItemId(); //returns id of an incorrect menu String Title = (String) item.getTitleCondensed(); //this returns the correct title. 

Any ideas are welcome.

+4
source share
2 answers

I had the same problem. Generated files from the assembly are not updated correctly.

I got the same effect if I reordered menu items in xml ... build and surprise. When you click on the menu, other codes are displayed than expected.

Please clean and try again.

+7
source

You must set a unique identifier for each menu item in onCreateOptionsMenu and onCreateContextMenu.

For instance:

  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 goes for onCreateOptionsMenu and onOptionsItemSelected. You must have a unique constant for each menu option.

Added:

You did not view this tutorial ? The idea is the same. You must set different identifiers 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 these identifiers 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 the official Android Menu guide and compare with your own code. You can also post your menu.xml , onCreateOptionsMenu and onOptionsItemSelected , so it would be easy to figure out your problem.

+1
source

All Articles