Butter Knife 是一个专注于 Android 系统 View 的注入框架,
让你从烦人的 findViewById 中解脱出来。同时还支持 View 的一些事件处理函数。
butterknife地址:https://github.com/JakeWharton/butterknife
以下介绍两种实现button的方法
老版本方法(InjectView)
在app目录下的build.gradle中添加如下依赖
dependencies {
compile 'com.jakewharton:butterknife:6.0.0'
}
在activity中添加按键
public class SimpleActivity extends Activity {
@InjectView(R.id.hello)
Button hello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
}
// hello的点击事件
@OnClick(R.id.hello)
void sayHello() {
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
}
新版本使用方法(bindView)
在module-level的build.gradle中添加如下依赖
apply plugin: 'android-apt'
dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
在project-level的build.gradle中添加如下依赖
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
在activity中的使用方法
public class SimpleActivity extends Activity {
@BindView(R.id.hello) Button hello;
@OnClick(R.id.hello)
public void sayHello() {
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
}
}