Android库项目中的菜单项ID?

时间:2022-06-28 22:44:35

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:

Android应用程序使用库项目来包含大部分应用程序代码,因为有两个版本的应用程序是从核心源构建的。自IntelliJ IDEA更新(至v11)后,我在以下每个案例陈述中收到此警告:

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?

好的,所以如果我不能通过他们的ID引用它们,我该如何引用它们?

1 个解决方案

#1


69  

Substitute the switch with an if/else if construct.

用if / else if结构替换开关。

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.

这是自ADT 14以来的必要条件,因为最终修饰符已从R类中的id中删除。

See Non-constant Fields in Case Labels

请参见案例标签中的非常量字段

#1


69  

Substitute the switch with an if/else if construct.

用if / else if结构替换开关。

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.

这是自ADT 14以来的必要条件,因为最终修饰符已从R类中的id中删除。

See Non-constant Fields in Case Labels

请参见案例标签中的非常量字段