Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

java - what causes "constant expression required" errors for the generated R.id.xxx values in switch statements?

We've got a multi-project app that we're moving to gradle. The build results in Java compilation errors like:

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.

One clue is that errors are only for switch values. For example there's no error using 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.

SOLUTION (2014-01-09)

our build.gradle for the app was applying the android-library plugin instead of the android plugin. it was this:

apply plugin: 'android-library'

changing it to this:

apply plugin: 'android'

fixed the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Library project resource identifiers are not constant static final ints, just static ints.

Convert the code that needs to switch on library resource ids to if-else structures.

Further reading: http://tools.android.com/tips/non-constant-fields


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...