ButterKnife使用详解及注意事项【2】

一.之前介绍过关于ButterKnife如何使用,有兴趣的可以去看看

地址:https://blog.csdn.net/wangxumh520/article/details/77926523

二.最近接手了公司的老项目,该项目中使用了黄油刀。运行时 遇到了一些问题,分享下

老项目中:IDE版本 2.3.2 Gradle:5.1.1 ButterKnife 8.8.1

迁移后:IDE版本3.3.1 Gradle 4.10.1 ButterKnife 9.0.0

为什么没有使用最新的10.1.0版本呢?因为该版本使用的Androidx 为了避免冲突,选择了9.0.0

三.ButterKnife9.0.0配置

1.项目的 build.gradle 中的配置:

buildscript {
  repositories {
    mavenCentral()
    google()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0'
  }
}

2.module 中的 build.gradle 中的配置

android {
    ....
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {
  implementation 'com.jakewharton:butterknife:9.0.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0'
}

注意:9.0.0版本的黄油刀使用了Lambab表达式,需要使用Java8

3.Library 中的注意事项

如果 library 中如果需要使用 butterknife 寻找控件,一定要添加 plugin

  • 在module 上方声明 ,目的是为了生成R2文件。
apply plugin: 'com.jakewharton.butterknife'
  • 还要在 module 下的 build.gradle 中添加 annotationProcessor,目的是为了自动生成java文件。
dependencies {
    annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0'
}
  • 不要尝试在 Library 中引入 ButterKnife,然后在 application 中通过依赖 Library 的方式引入,因为上条注意事项重的两项,必须添加在使用的 ButterKnife 的自己 module 中才能生效
  • Library 中需要使用 R2.id.* 才能找到控件,原因是 ButterKnife 的注解必须是常量,在Library 中的 R.id.* 并不是常量,生成的 R2 才是 final 修饰的常量。
@BindView(R2.id.tv_xxx)
TextView tvXXX;
  • switch 不能使用,同样是因为不是常量的原因,需要使用 if 替代,但是里面的判断还是要用 R.id.*
@OnClick(R2.id.xxx)
void onClick(View v) {
    if (v.getId() == R.id.xxx) {
        xxx();
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值