ButterKnife具有强大的绑定事件和资源文件功能,同时几乎不会影响程序运行效率,ButterKnife用到的注解并不是在运行时反射的,而是在编译的时候生成新的class,使用ButterKnife可以使代码更清晰易读
impelementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
遇到一个问题
The given artifact contains a string literal with a package reference ‘android.support.v4.content
解决方法:更新ButterKnife版本
implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'
@BindView(R.id.main_tv)
TextView textView;
ButterKnife.bind(this)必须在初始化绑定布局文件之后,否则会报错
需要在使用控件前绑定,不然会报空指针异常
ButterKnife.bind(this);
Unbinder unbinder = ButterKnife.bind(this,view);
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();//视图销毁时必须解绑
}
在Fragment中需要在视图销毁时解绑Butterknife,否则会造成内存泄漏
1、在Activity 类中绑定 :ButterKnife.bind(this); 必须在setContentView(); 之后绑定;且父类bind绑定后,子类不需要再bind。
2、在非Activity 类(eg:Fragment、ViewHold)中绑定: ButterKnife.bind(this,view);这里的this不能替换成getActivity()。
3、在Activity中不需要做解绑操作,在Fragment 中必须在onDestroyView()中做解绑操作。
4、使用ButterKnife修饰的方法和控件,不能用private or static 修饰,否则会报错。错误: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)
5、setContentView()不能通过注解实现。(其他的有些注解框架可以)
6、使用Activity为根视图绑定任意对象时,如果你使用类似MVC的设计模式你可以在Activity 调用ButterKnife.bind(this, activity),来绑定Controller。
7、使用ButterKnife.bind(this,view)绑定一个view的子节点字段。如果你在子View的布局里或者自定义view的构造方法里 使用了inflate,你可以立刻调用此方法。或者,从XML inflate来的自定义view类型可以在onFinishInflate回调方法中使用它。
名称 | 解析 |
---|---|
@BindViews | 绑定多个view id 为一个view的list变量 @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews; |
@BindView | 绑定一个view id为一个view变量@BindView(R.id.title) TextView title; |
@BindArray | 绑定String中的array数组 @BindArray(R.array.city)String[] citys; |
@BindBitmap | 绑定图片资源文件, @BindBitmap(R.mipmap.wifi) Bitmap bitmap; |
@BindBool | 绑定真假boolean @BindBool(R.bool.boor) |
@BindColor | 绑定颜色 @BindColor(R.color.red) |
@BindDimen | 绑定尺寸 @BindDimen(R.dimen.spacer) Float spacer; |
@BindDrawable | 绑定Drawable @BindDrawable(R.drawable.graphic) Drawable graphic |
@BindFloat | 绑定Float |
@BindInt | 绑定Int |
@BindString | 绑定一个String id为String变量, @BindString(R.string.app_name) String msg |
@BindAnim | 绑定动画 |
@BindFont | 绑定字体文字 |
绑定事件,一共有12个监听事件
名称 | 解析 |
---|---|
@OnClick | 点击事件 |
@OnCheckedChanged | 选中,选中取消 |
@OnEditorAction | 软键盘的功能按键 |
@OnFocusChange | 焦点改变 |
@OnItemClick | Item被点击事件(注意这里有坑,如果item里面有Button等这些有点击的控件事件的,需要设置这些控件属性focusable为false) |
@OnItemLongClick | tem长按,返回真则可以拦截onItemClick |
@OnItemSelected | Item被选择事件 |
@OnLongClick | 长按事件 |
@OnPageChange | 页面改变事件 |
@OnTextChanged | EditText里面的文本变化事件 |
@OnTouch | 触摸事件 |
@Optional | 选择性注入,如果当前对象不存在,就会抛出一个异常,为了压制这个异常,可以在变量或者方法上加入注解,让注入变成选择性的,如果目标View存在,则注入, 不存在,则什么事情都不做 |