当前位置: 首页 > 工具软件 > ButterKnife > 使用案例 >

ButterKnife

慕容耘豪
2023-12-01

ButterKnife具有强大的绑定事件和资源文件功能,同时几乎不会影响程序运行效率,ButterKnife用到的注解并不是在运行时反射的,而是在编译的时候生成新的class,使用ButterKnife可以使代码更清晰易读

使用

1.添加依赖

    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'

 2.使用

 @BindView(R.id.main_tv)
 TextView textView;

ButterKnife.bind(this)必须在初始化绑定布局文件之后,否则会报错 

需要在使用控件前绑定,不然会报空指针异常
ButterKnife.bind(this);

Fragment中绑定ButterKnife 

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回调方法中使用它。
 

 3.常用注解

名称解析
@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焦点改变
@OnItemClickItem被点击事件(注意这里有坑,如果item里面有Button等这些有点击的控件事件的,需要设置这些控件属性focusable为false)
@OnItemLongClicktem长按,返回真则可以拦截onItemClick
@OnItemSelectedItem被选择事件
@OnLongClick长按事件
@OnPageChange页面改变事件
@OnTextChangedEditText里面的文本变化事件
@OnTouch触摸事件
@Optional选择性注入,如果当前对象不存在,就会抛出一个异常,为了压制这个异常,可以在变量或者方法上加入注解,让注入变成选择性的,如果目标View存在,则注入, 不存在,则什么事情都不做
 类似资料:

相关阅读

相关文章

相关问答