1.安装AS的插件
File → Setting → Plugins 然后输入Android ButterKnife Injections查找这个插件,之后安装。
2.配置工程的build.gradle
在工程的build.gradle里面加上依赖
代码如下:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
//新增
classpath 'com.jakewharton:butterknife-gradle-plugin:10.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
//新增
maven { url "https://jitpack.io" }
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3.配置项目的build.gradle
在项目的build.gradle 里面的android闭包中设置jdk编译版本为1.8
加入如下代码:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dependencies闭包里面加入插件依赖代码:
//butterknife 绑定视图依赖BindView,告别findById
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
4.布局文件添加控件id
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
5.绑定控件
进入到MainActivity.java
鼠标光标放到设置布局文件的方法参数中
然后单击右键选择Generate
然后选择Generate ButterKnife Iniertions
设置好了后点击confirm即可。