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.特別注意
在異步請求中歧焦,尤其是網(wǎng)絡(luò)請求,一般異步回來網(wǎng)絡(luò)結(jié)果時(shí),我們需要更新UI眷柔,這個時(shí)候,如果界面已經(jīng)調(diào)用了onDestroy()或者onDestroyView(),相當(dāng)于頁面已經(jīng)銷毀酝润,調(diào)用了unbind()方法了祟绊,如果我們還有更新UI的話楼入,就會報(bào)空指針異常。所以必須在異步回調(diào)里牧抽,來判斷是否已經(jīng)解綁嘉熊,如果已經(jīng)調(diào)用解綁了,那就不能再執(zhí)行相關(guān)操作了扬舒。
方法是在unbind()之后將mUnbinder=null阐肤;
在異步回調(diào)時(shí),首先判斷mUnbinder==null,則return孕惜;