android - Android库项目中的菜单项ID?

标签 android intellij-idea

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

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

代码如下:

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);
    }
}

好的,如果我无法通过他们的 ID 引用它们,我该如何引用它们?

最佳答案

if/else if 构造替换 switch

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

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

Non-constant Fields in Case Labels

关于android - Android库项目中的菜单项ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476912/

相关文章:

java - 实例化内部类时遇到问题

python - PyCharm/IntelliJ 对 Python 文档字符串使用什么样式?

intellij-idea - IntelliJ - 查找未记录的公共(public)方法

grails - 在 IntelliJ 中使用插件依赖项设置 Grails 1.1 应用程序

Android Studio 3.0 Preview - Studio 没有写入权限

android - RxJava 链请求和更新 UI

minTime > 0 的 android LocationManager.requestLocationUpdates 未按预期工作

android - 错误 : Failed to find target with hash string 'android-27'

java - 搜索翻译的id时应该返回null还是-1?

android - 使用 intellij 导出签名版本 APK 时出现问题