nlucaroni nlucaroni - 1 year ago 59
Android Question

Android Option Menu not working properly; what am I missing?

I've been away from Java for some time --functional programming has been my muse-- and recently decided to jump back in with an android application. Things are going well. Javas syntax is mostly back in my brain, OO design principles are a little rusty, but I'm not afraid of re-factoring.

One problem I hit has been with the option menus in the platform. I load them from an XML file through a menu-inflator in my main activity (below), and I can see them! But, when I press them things get weird --but not like seeing your grandmother make-out with your best friend, much less weird.

For some reason, when I press the first button, I get the friendly

message in the code sample below, "That's not an option, moron!". And when I press the second, the message is "Adding One". I'm off by one somehow! But, but how!? but why!?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">
<item android:id="@+id/add_single_id"
android:title="@string/add_one" />
<item android:id="@+id/add_multi_id"
android:title="@string/add_multi" />

... which is loaded by the menu inflator...

public boolean onCreateOptionsMenu( Menu menu ){
MenuInflater inflater = getMenuInflater();
inflater.inflate(, menu);
return true;

... and finally the listener for items selected.

public boolean onOptionsItemSelected( MenuItem item ){
switch( item.getItemId() ){
Toast.makeText(this, "Adding One", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Adding n", Toast.LENGTH_LONG).show();
Intent i = new Intent(this, SelectMulti.class);
startActivityForResult(i, ACTIVITY_LOADMULTI);
Toast.makeText(this, "That's not an option, moron!", Toast.LENGTH_LONG).show();
return false;
return true;

Answer Source

This happen to me many times when I am developing android on eclipse, and clean and rebuilding a project fixes it as it will recreate android Resource file and correctly map to your UI id's.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download