Github地址:https://github.com/JakeWharton/butterknife
1.打开androidStudio Settings->Plugins
搜索Butterknife 安装Android ButterKnife Zelezny(重启生效)
2.修改项目(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'
}
3.修改工程(project)的build.gradle
buildscript {
repositories {
mavenCentral()
google()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0'
}
}
4.修改项目(app)的build.gradle
apply plugin: 'com.jakewharton.butterknife'
android {
...
}
5.鼠标右键选中布局id Generate→Generate ButterKnife Injections
6.elment–对象 onclick–点击事件
7.点击confirm
package com.qdxx.butterknifedemo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_msg)
TextView tvMsg;
@BindView(R.id.btn_click)
Button btnClick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick({R.id.tv_msg, R.id.btn_click})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.tv_msg:
break;
case R.id.btn_click:
break;
}
}
}
8.完善demo
package com.qdxx.butterknifedemo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_msg)
TextView tvMsg;
@BindView(R.id.btn_click)
Button btnClick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick({R.id.tv_msg, R.id.btn_click})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.tv_msg:
break;
case R.id.btn_click:
click();
break;
}
}
private void click() {
tvMsg.setText("click button");
Toast.makeText(this, "click button", Toast.LENGTH_SHORT).show();
}
}