Home » Android » intellij idea – Menu item IDs in an Android library project?

intellij idea – Menu item IDs in an Android library project?

Posted by: admin April 23, 2020 Leave a comment

Questions:

The Android app uses a library project to contain most of the app code, as there are two versions of the app built from the core source. Since an IntelliJ IDEA update (to v11) I’m getting this warning on each of the case statements below:

Resource IDs cannot be used in a switch statement in Android library modules

Here’s the code:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_item_one:   // Build error here
            // Do stuff
            return true;
        case R.id.menu_item_two:   // Build error here
            // Do stuff
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

OK, so if I can’t reference them via their ID, how DO I reference them?

How to&Answers:

Substitute the switch with an if/else if construct.

int id = item.getItemId();
if(id == R.id.menu_item_one) {
    // ...
}
else if(id == R.id.menu_item_two) {
    // ...
}

This is neccessary since ADT 14 because the final modifier was removed from id’s in the R class.

See Non-constant Fields in Case Labels