推荐一篇比较好的bufferKnife学习文章点击打开链接
我作为一个学习者认为 ButterKnife要掌握以下注解的使用
一类是:替代findViewById方法
一类是:代替setOnClickedListener setOnLongClickedListener setOnItemClickedListener 等等一类点击 监听器
除了Onclick方法可以简便,还有很多,具体我们在监听器那里已经学习了就不多说
OnCheckedChanged |
Bind a method to an
OnCheckedChangeListener on the view for each ID specified.
|
OnClick |
Bind a method to an
OnClickListener on the view for each ID specified.
|
OnEditorAction |
Bind a method to an
OnEditorActionListener on the view for each ID specified.
|
OnFocusChange |
Bind a method to an
OnFocusChangeListener on the view for each ID specified.
|
OnItemClick |
Bind a method to an
OnItemClickListener on the view for each ID specified.
|
OnItemLongClick |
Bind a method to an
OnItemLongClickListener on the view for each ID specified.
|
OnItemSelected |
Bind a method to an
OnItemSelectedListener on the view for each ID specified.
|
OnLongClick |
Bind a method to an
OnLongClickListener on the view for each ID specified.
|
OnPageChange |
Bind a method to an
OnPageChangeListener on the view for each ID specified.
|
OnTextChanged |
Bind a method to an
TextWatcher on the view for each ID specified.
|
OnTouch |
Bind a method to an
OnTouchListener on the view for each ID specified.
|
ButterKnife 要掌握的注解:
需要注意的是View变量声明的时候不能为private或者static.
1、当前的view 进行注入
ButterKnife.inject(this);
ButterKnife.inject(this, view);
2、代替findViewById
@InjectView(R.id.butter_text_view_2)
TextView mTextView2
@InjectViews({R.id.label_first_name, R.id.label_middle_name, R.id.label_last_name})
List<TextView> labelViews;
3、设置点击事件
除了点击事件@OnClick,还有ListView的点击@OnItemClick, CheckBox的@OnCheckedChanged等等.
可以一次指定多个id,为多个View绑定一个事件处理方法,比如:
注意这里方法仍然不能是private和static, 方法名称可以任意取,并且可以有一个参数View,也可不写.
所有listener的参数都是optional的,可以写,也可以不写.
并且写的时候可以直接写一个具体的子类,比如参数View可以写成Button,这里的cast是自动完成的,所以很灵活
@OnClick(R.id.basic_finish_a_button)
void finishA(View view) {
finish();
}
@OnClick({R.id.button_enable, R.id.button_disable, R.id.button_alpha_0, R.id.button_alpha_1})
void editViewsClicked() {
Toast.makeText(this, "You click the Button!", Toast.LENGTH_SHORT).show();
}
4、注入重置(Injection Rest):
可以用reset()方法将ButterKnife注入的View引用设置为null.
比如在Fragment的onCreateView()里调用ButterKnife.inject()方法注入了一些View,在onDestroyView()里想把它们置为null,可以直接调用ButterKnife.reset(this);方法.
5、选择性注入(Optional Injection):
默认情况下,@InjectView和listener的注入都是必须的,如果target view没有被发现,则会报错.
为了抑制这种行为,可以用@Optional注解来标记field和方法,让注入变成选择性的,如果targetView存在,则注入, 不存在,则什么事情都不做.
当布局被复用时,这个@Optional注解很有用.
android studio 有一个butterKnife插件可以 批量生成 @InjectView 过程如下:
自动生成如下
@InjectView(R.id.bt_button1) Button btButton1; @InjectView(R.id.bt_button2) Button btButton2; @InjectView(R.id.bt_button3) Button btButton3; @InjectView(R.id.bt_button4) Button btButton4;