转载请注明出处http://blog.csdn.net/u012532631/article/details/77196426
今天学习了一下使用ButterKnife,使用场景分别为Activity和Fragment
添加项目依赖
dependencies {
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknifecompiler:8.8.1'
}
在Activity中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
在Fragment中
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = setFragmentLayoutInFlater(inflater,container);
//返回一个Unbinder值(进行解绑),注意这里的this不能使用getActivity()
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
if (unbinder != null) {
unbinder.unbind();
}
super.onDestroyView();
}
请注意这里一定要提前判断unbinder 是否为空,因为若是在异步回调的时候页面可能已经销毁,此时调用unbind()可能引发空指针异常!