Java 是什么导致 switch 语句中生成的 R.id.xxx 值出现“需要常量表达式”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21005205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what causes "constant expression required" errors for the generated R.id.xxx values in switch statements?
提问by user3174822
We've got a multi-project app that we're moving to gradle. The build results in Java compilation errors like:
我们有一个多项目应用程序,我们正在将其迁移到 gradle。构建会导致 Java 编译错误,例如:
AFragment.java:159: constant expression required
case R.id.aBtn:
We've confirmed that the constants reported in errors are in the generated R.java
.
我们已经确认错误中报告的常量在生成的R.java
.
One clue is that errors are only for switch values. For example there's no error using findViewById(R.id.aBtn)
.
一条线索是错误仅针对开关值。例如,使用findViewById(R.id.aBtn)
.
also note that the constants are from the main project, not one of the library projects.
另请注意,常量来自主项目,而不是库项目之一。
for anyone looking to get rid of the errors laalto's suggestion will solve it.
对于任何希望摆脱错误的人来说,拉尔托的建议将解决它。
the link he provided, together with the fact that eclipse doesn't show the errors that occur when building with gradle gave me another clue. the R.java generated by eclipse defines the main project constants as 'final' but the gradle generated values are not 'final'. the real solution must be in correcting the gradle build files.
他提供的链接以及 eclipse 没有显示使用 gradle 构建时发生的错误这一事实给了我另一个线索。Eclipse 生成的 R.java 将主要项目常量定义为“final”,但 gradle 生成的值不是“final”。真正的解决方案必须是纠正 gradle 构建文件。
SOLUTION (2014-01-09)
解决方案 (2014-01-09)
our build.gradle for the app was applying the android-library plugin instead of the android plugin. it was this:
我们应用的 build.gradle 应用了 android-library 插件而不是 android 插件。是这样的:
apply plugin: 'android-library'
应用插件:'android-library'
changing it to this:
将其更改为:
apply plugin: 'android'
应用插件:'android'
fixed the problem.
解决了这个问题。
回答by Ridcully
This happens if you use Resources from a Library project. In that case, the the ids in the R
class are not really constants and thus cannot be used in a switch statement.
如果您使用库项目中的资源,就会发生这种情况。在这种情况下,R
类中的 id并不是真正的常量,因此不能在 switch 语句中使用。
回答by laalto
Library project resource identifiers are not constant static final int
s, just static int
s.
图书馆项目资源标识符不是常数static final int
s,只是static int
s。
Convert the code that needs to switch on library resource ids to if
-else
structures.
将需要开启库资源ids的代码转换为if
-else
结构体。
Further reading: http://tools.android.com/tips/non-constant-fields