Butterknife也是JakeWharton大神开源的一个Android项目。
用于
- 减少findViewById的使用
- 批处理多个view的操作
- 减少内部类和监听类的使用
- 减少资源的id的重复使用
话不多说,直接介绍其使用方法。
gradle使用
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
提供的三种方法
ButterKnife.bind();
ButterKnife.apply();
ButterKnife.findById();
绑定view方法的注解
@OnCheckedChanged
@OnClick
@OnEditorAction
@OnFocusChange
@OnItemClick
@OnItemLongClick
@OnItemSelected
@OnLongClick
@OnPageChange
@OnTextChanged
@OnTouch
绑定view和资源变量的注解
@BindArray()
@BindBitmap()
@BindBool()
@BindColor()
@BindDimen()
@BindDrawable()
@BindFloat()
@BindInt()
@BindString()
@BindView()
@BindViews()
配套的使用了这些注解就要使用Butterknife.bind()方法实现绑定。
下面就来介绍下其具体用法吧。
public class MyActivity extends Activity {
private static final ButterKnife.Action<View> ALPHA_FADE = new ButterKnife.Action<View>() {
@Override public void apply(@NonNull View view, int index) {
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setFillBefore(true);
alphaAnimation.setDuration(500);
alphaAnimation.setStartOffset(index * 100);
view.startAnimation(alphaAnimation);
}
};
@BindView(R.id.title) TextView title;
@OnClick(R.id.hello)
void sayHello() {
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
ButterKnife.apply(headerViews, ALPHA_FADE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
}
}
上面的代码基本上已经把Butterknife的主要功能已经介绍完了,它用起来还是非常方便的。
上面只介绍了一个BindView、OnClick、ButterKnife.bind和ButterKnife.apply方法。
其他的使用都是类似的就不多做介绍了,感兴趣的同学可以多去实验实验。
ButterKnife的官网也非常详细的介绍了其使用方法,所以本文也不做过多的介绍了。需要深入了解的可以去官网或者查看源码加深理解。
Butterknife官网
Butterknife github
Butterknife 翻译
Android Studio安装Android ButterKnife Zelezny插件,实现快速插入。