1.Gradle 配置
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
2.绑定
- Activity 中使用,一定要在
setContentView()
之后再写ButterKnife.bind(this);
- Fragment 中使用
View contentView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.test, null);
ButterKnife.bind(this, contentView);
- 自定义view中,与fragment相似
View contentView= LayoutInflater.from(getContext()).inflate(R.layout.test, this);
ButterKnife.bind(this,contentView);
3.解绑
public class BaseFragment extends Fragment {
public static final String TAG = "BaseFragment";
protected Unbinder mUnbinder;
@Override
public void onDestroyView() {
if (this.mUnbinder != null) {
this.mUnbinder.unbind();
}
super.onDestroyView();
}
}
4.特别注意
在异步请求中,尤其是网络请求,一般异步回来网络结果时,我们需要更新UI,这个时候,如果界面已经调用了onDestroy()或者onDestroyView(),相当于页面已经销毁,调用了unbind()方法了,如果我们还有更新UI的话,就会报空指针异常。所以必须在异步回调里,来判断是否已经解绑,如果已经调用解绑了,那就不能再执行相关操作了。
方法是在unbind()之后将mUnbinder=null;
在异步回调时,首先判断mUnbinder==null,则return;