ButterKnife能够帮助你进行字段和方法的绑定,使用注解来android中控件的查找和方法的绑定。
java
ButterKnife如今的版本是7.0.1.下载地址:http://jakewharton.github.io/butterknife/ 下载jar包。android
在androidstudio中的使用,直接将jar包导入到libs文件夹里,而后直接设置工程属性添加这个包就好了。git
使用方法:github
在Activity里
iview
@Bind(R.id.change) Button change; @Bind(R.id.next) Button next;
变量使用@Bind来绑定,变量不能够为private类型。函数
在onCreate里面调用
this
ButterKnife.bind(this);
在onDestroy里面调用spa
ButterKnife.unbind(this);
若是是在Fragment里面调用
指针
在onCreateView调用code
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
其余的功能能够自行发掘