欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Android Button设置点击监听器用switch case R.id.xxxx报错:Constant expression required

Android Button设置点击监听器用switch case R.id.xxxx报错:Constant expression required

2025/2/24 0:49:24 来源:https://blog.csdn.net/qq_38666896/article/details/140740077  浏览:    关键词:Android Button设置点击监听器用switch case R.id.xxxx报错:Constant expression required

背景

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

Old code - AGP 3.5.2 & Gradle 6.5
Old code - AGP 3.5.2 & Gradle 6.5
New code -  AGP 8.4.0 & Gradle 8.6
New code -  AGP 8.4.0 & Gradle 8.6

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

Suggetion of old code
Suggetion of old code

建议说明

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) {//点击操作}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词