關於IllegalStateException: Bindings already cleared
我們在使用用viewpager的時候 往往裏面會加載多個Fragment,如果在Fragment數量超過3個fragment的時候,我們發現,在相互切換的時候會報錯報錯:java.lang.IllegalStateException: Bindings already cleared.
檢查發現,由於(viewpager有回收fragment的機制)
03-29 10:28:35.535 1896-1896/com.xxx.xxx D/2次加載: onCreateView------>root not null
03-29 10:28:35.958 1896-1896/com.xxx.xxx D/2次加載: onCreateView------>root not null
在第一次(第一次回收fragment正常)unbind的時候沒有報錯,第二次(第二次回收fragment報Bindings already cleared. )的時候就報錯,也就是第二次沒有bind成功。
這個時候我們應對當前代碼進行判斷處理:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.activity_myrecord, container, false);
}
else {
Log.d("2次加載"," onCreateView------>root not null");
// 二次加載刪除上一個子view
ViewGroup viewGroup = (ViewGroup) view.getParent();
if (viewGroup != null) {
viewGroup.removeView(view);
}
}
initView(view);
return view;
}
再次運行 問題解決!