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

41 篇文章 0 订阅
9 篇文章 0 订阅

背景

问题:在旧项目 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的判断

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn) {
            //点击操作
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值