一、引用
ButterKnife的引用分为两种情况:
1. 在app模块使用
在app模块的build.gradle中加入代码如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
// ...省略部分代码
// 需要加入的代码,加入此代码,在项目中可以使用Lambada表达式
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// ...省略部分代码
// 需要加入的代码,引入ButterKnife库
api 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}
2. 在library中使用,app模块引入library
在项目的build.gradle中加入代码如下:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
// 需要加入的代码,此代码保证在app和library模块中应用ButterKnife插件时编译不报错
classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0'
}
}
在library模块的build.gradle中加入代码如下:
apply plugin: 'com.android.library'
// 需要加入的代码,此代码保证运行时可以正常调用ButterKnife注解的方法
apply plugin: 'com.jakewharton.butterknife'
android {
compileSdkVersion 29
// ...省略部分代码
// 需要加入的代码,加入此代码,在项目中可以使用Lambada表达式
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// ...省略部分代码
// 需要加入的代码
api 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}
在app模块的build.gradle中加入代码如下:
apply plugin: 'com.android.application'
// 需要加入的代码,此代码保证运行时可以正常调用ButterKnife注解的方法
apply plugin: 'com.jakewharton.butterknife'
android {
compileSdkVersion 28
// ...省略部分代码
// 需要加入的代码,加入此代码,在项目中可以使用Lambada表达式
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// ...省略部分代码
// 需要加入的代码
implementation project(':mylib')
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}
【注意】如果不声明JDK编译版本,运行时将报错:java.lang.BootstrapMethodError: Exception from call site #1 bootstrap method
,因为ButterKnife使用了JDK1.8的新特性。 另外,声明了JDK编译版本的好处是可以在项目中使用lambada表达式,非常方便。
二、使用
ButterKnife在使用过程中需要注意以下几点:
- 使用ButterKnife注解不能加private、static限定符,否则会报
@BindView fields must not be private or static
。 - Butterknife.bind(this) 需要在 setContentView() 之后调用,否则注解绑定ID无效,将会报
IllegalStateException: xxx was not found
。 - ButterKnife使用后要及时销毁。
- 新版本绑定ID时可以直接使用R.id,也可以使用R2.id。
示例如下:
public class MainActivity extends AppCompatActivity {
private Unbinder unbinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
unbinder = ButterKnife.bind(this);
}
@Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
@OnClick(R.id.btn_senior_ui)
void openShader() {
startActivity(new Intent(MainActivity.this, SeniorUIActivity.class));
}
}