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;