【重学Android】03.高版本 Android Studio 不能使用引用库资源ID的问题
问题背景
由于直接下载的最新版本Android Studio,然后直接创建的新项目,因此默认的工程配置相比以前的老版本有了不少的变化,Gradle的新版本使用,导致一些配置项也发生了变化,加上谷歌针对gradle.properties文件的一些配置也有了变化。
而这次我因为使用了一些第三方库,然后有些资源想偷懒,直接引用第三方库中的,结果发现代码自动提示怎么都弹不出来,一开始还以为工程出问题了,但是几番折腾后发现还是不行,这才意识到可能是哪个配置出了问题。并且一直提示如下信息:
Attribute value must be constant
解决
经过一番搜索之后,发现根本原因是因为新版本 Android Studio 将 R 类中的资源设置成了非 final 修饰的变量,这就是导致 switch case 中无法作为判断条件的原因。
然后在gradle.properties文件中会看到这样一段描述和一个配置项。
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.nonFinalResIds=true
就是这两个配置项导致AS不会将第三方库中的资源ID编译为Final类型的。我们只需要将值改为false,然后再进行同步即可。