背景
问题:在旧项目 R.id.btn 还能直接引用xml中定义的Button id,但是新项目发现都报错了。


原因:因为Gradle 8.0之后不支持这种写法,为了改善增量编译的性能,而弃用这种恒定的R.id。

建议说明
Resource IDs will be non-final by default in Android Gradle Plugin version 8.0, avoid using them in switch case statements
Inspection info: Avoid the usage of resource IDs where constant expressions are required. A future version of the Android Gradle Plugin will generate R classes with non-constant IDs in order to improve the performance of incremental compilation.Issue id: NonConstantResourceId
Vendor: Android Open Source Project
Contact: https://groups.google.com/g/lint-dev
Feedback: https://issuetracker.google.com/issues/new?component=192708
可选操作:Suppress NonConstantResourceId with an annotation,但是在高版本Gradle还是波浪红线报错了,提示:Constant expression required。
新代码信息:API 34,Java 8(所以不是JDK17的switch语句更新问题吧)
解决方案
用 if esle替换switch的判断
@Overridepublic void onClick(View v) {if (v.getId() == R.id.btn) {//点击操作}}