一.之前介绍过关于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();
}
}