ButterKnife可以帮助你进行字段和方法的绑定,使用注解来android中控件的查找和方法的绑定。
ButterKnife现在的版本是7.0.1.下载地址:http://jakewharton.github.io/butterknife/ 下载jar包。
在androidstudio中的使用,直接将jar包导入到libs文件夹里,然后直接设置工程属性添加这个包就行了。
使用方法:
在Activity里
@Bind(R.id.change)
Button change;
@Bind(R.id.next)
Button next;
变量使用@Bind来绑定,变量不可以为private类型。
在onCreate里面调用
ButterKnife.bind(this);
在onDestroy里面调用
ButterKnife.unbind(this);
如果是在Fragment里面调用
在onCreateView调用
view = inflater.inflate(R.layout.fancy_fragmentcontainer)ButterKnife.(view)
在onDestroyView里面调用
ButterKnife.unbind(this);
官网的建议是
Fragments have a different view lifecycle than activities. When binding a fragment in onCreateView
, set the views to null
in onDestroyView
.
片段和Activity有着不同的生命周期,所以要在onDestroyView里面调用unbind函数,这是一种建议并不是一定要这么做,你也可以不实现onDestroyView这个函数。如果onCreateView里面view是全局的或者你在其它地方调用了,那么onDestroyView调用unbind函数,那么就会出现空指针异常。
在Adapter里面调用
ViewHolder {
@Bind(R.id.title) TextView name;
@Bind(R.id.job_title) TextView jobTitle;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
在geiview里面初始化这个类就可以了。
ButterKnife也可以绑定函数和资源,这里就给出一些实例
@OnClick(R.id.submit)
submit(View view) {
}
@OnClick({R.id.door1R.id.door2R.id.door3})
pickDoor (DoorView door){
(door.hasPrizeBehind()) {
Toast.makeText(LENGTH_SHORT).show()} {
Toast.makeText(LENGTH_SHORT).show()}
}
@OnItemSelected(R.id.list_view)
onItemSelected(position) {
}
@BindString(R.string.title) String title
@BindDrawable(R.drawable.graphic) Drawable graphic
@BindColor(R.color.) red
@BindDimen(R.dimen.spacer) Float spacer
其他的功能可以自行发掘