menuitem id in xml format can't be an integer? huh. really?
ok, in menu.add, you add an integer menuitem id.
But when you specify the menu in xml, @+id can't take an integer, so you can't test the id for the menu item as an integer in a switch statement.
What obvious thing am I missing, because surely an inconsistency this bone-stupid couldn't have passed muster with all those wonderful geniuses at Google.
on top of that, when I give the menu 开发者_StackOverflowitem a name like "@+id/myMenuItem", item.getItemId() returns an integer, a long one, which I guess is a representation of the hex pointer.
M
You can't specify the id attribute in XML as an integer because all ids are (in the build process) generated into an integer, and then placed into R.java for access later. If they let you name it an integer, then you wouldn't be creating legal Java code (because Java variables can't just be a number).
In other words, if you name an id "@+id/something", then in R.java there is a static variable "something" which contains the integer id for the id. Then in code, you access it like this when the user clicks the menu item:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.something: {
// Do something here
return true;
}
return super.onOptionsItemSelected(item);
}
@id
values have to map to Java names (@id/foo
turns into R.id.foo
), and you can't have a Java name that is pure numeric. I'm not even sure it can start with a number.
Check out this example:
private static final int EDIT_ID = Menu.FIRST + 3;
private static final int DELETE_ID = Menu.FIRST + 4;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit").setAlphabeticShortcut(
'e');
menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
.setAlphabeticShortcut('d');
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case EDIT_ID:
edit(info.id);
return (true);
case DELETE_ID:
delete(info.id);
return (true);
}
return (super.onOptionsItemSelected(item));
}
精彩评论