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 default 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="http://schemas.android.com/apk/res/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" />
</menu>
… which is loaded by the menu inflator…
public boolean onCreateOptionsMenu( Menu menu ){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
… and finally the listener for items selected.
public boolean onOptionsItemSelected( MenuItem item ){
switch( item.getItemId() ){
case R.id.add_single_id:
Toast.makeText(this, "Adding One", Toast.LENGTH_LONG).show();
add_single();
break;
case R.id.add_multi_id:
Toast.makeText(this, "Adding n", Toast.LENGTH_LONG).show();
Intent i = new Intent(this, SelectMulti.class);
startActivityForResult(i, ACTIVITY_LOADMULTI);
break;
default:
Toast.makeText(this, "That's not an option, moron!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
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.