前言
butterknife_logo.png
使用Butterknife之前我们先得了解一下版本问题,8.4.0以前和8.4.0以后
- 8.4.0之前(包含8.4.0):不支持在
library类型的module中使用 - 8.4.0之后(不包含8.4.0):支持在
library类型的module中使用
关于8.4.0及其之前的版本,使用比较简单,这里不做单独解释
随着android的不断发展,我们的app越做越大,模块化、组件化的架构设计被越来越多的项目采用,以便减少项目多人协作并行开发带来的很多麻烦,我们始终是要适应新事物的,这里我们就讲解一下模块化架构的android项目如何使用当前最新的版本10.2.0
首先打开Butterknife的github官网:https://github.com/JakeWharton/butterknife
可以看到readme.md说明文档
1.创建android项目myproject,主module名称为为app,并创建一个名称为library的module,app依赖library
在app中使用
- 在项目的主module即
app的build.gradle中加入
android {
...
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 //需要
targetCompatibility JavaVersion.VERSION_1_8 //需要
}
}
dependencies {
implementation 'com.jakewharton:butterknife:10.2.0' //需要
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0' //需要
}
注意:一定要使用
Java8及以上版本
在app中需要使用butterknife的Activity中加入
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//需要加入
ButterKnife.bind(this);
}
至此,我们可以通过Android ButterKnife Zelezny插件快速注解我们的组件
如果想在library中也使用butterknife请往下看
- 在项目工程
myproject的build.gradle中加入
buildscript {
repositories {
mavenCentral() //需要
google()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0' //需要
}
}
3.在library对应的build.gradle中加入
apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'//需要
...
//省略
...
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 //需要
targetCompatibility JavaVersion.VERSION_1_8 //需要
}
}
dependencies {
implementation 'com.jakewharton:butterknife:10.2.0' //需要
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0' //需要
}
注意:
implementation和api的区别,如果在library中使用api,依赖library的其他module将无需重复引入
- 在
library中创建LibraryActivity并在并在布局文件中添加两个Button
具体创建步骤,这里省略
和在主module的app中一样,在LibraryActivity中入ButterKnife.bind(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
//需要加入
ButterKnife.bind(this);
}
- 使用
Android ButterKnife Zelezny插件快速生成组件id引用
然后我们会看到生成的组件引用报错了,R文件对应的 id 无法识别
butterknife_library_error.png
-
替换注解中的
R为R2
注意只修改@BindView和@OnClick后面括号中的R,switch中的R不要改 -
对于Switch中的错误,我们将鼠标放到报错的地方,使用
Alt+Enter快捷键,快速替换成if……else
replace_switch.png
注意:为什么
switch语句使用R文件的ID会报错,因为在library中的ID值都不是final类型的,但是swicth语句的case要求必须是常数,所以在library中switch无法使用,但是在主module对应的app中所有ID都是常数,所以可以使用switch语句
然后 rebuild 项目
最终效果如下,即表示ButterKnife在library中正常工作
butterknife_library_correct.png
** 如果你觉得这篇文章对你有帮助或启发,关注一下呗,谢谢 _ 😄 _ **










网友评论