DialogFragment can not be attached to a container view
問題始末
在一個DialogFragment中,顯示了另一個Dialog,另一個Dialog顯示時,點選确定按鈕則将目前的Dialog再次顯示
僞代碼結構
class MyDialogFragment extends DiabogFragment {
View contentView;
FragmentActivity activity;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (contentView == null) {
contentView = inflater.inflate(getLayoutId(), container, false);
}
return contentView;
}
......
public void onBtnClick() {
DialogUtils.showMsgDialog("Msg", new OnOkBtnClick(){
public void onClick(Dialog dialog) {
DialogUitls.showDialogFragment(MyDialogFragment.this, activity);
dialog.dismiss();
}
});
dismiss();
}
}
問題
第一次顯示時沒有問題,但是當顯示了
MsgDialog
,點選
Button
再次顯示
Dialog
時,報
DialogFragment can not be attached to a container view
。
原因
if (contentView == null) {
contentView = inflater.inflate(getLayoutId(), container, false);
}
再次顯示
Dialog
時,并沒有重新建立視圖,而
DialogFragmnet
在
onActivityCreated
時判斷視圖是否有
Parent
。而因為原來的contentView對象沒有被銷毀,通過它
getParent
是不為
null
,是以抛出了此異常。
解決方式1
将contentView放在局部變量。
解決方式2.
// 先調用一下父類方法(因為恒傳回空,就不會存在問題)
contentView = super.onCreateView(inflater, container, savedInstanceState);
if (contentView == null) {
contentView = inflater.inflate(getLayoutId(), container, false);
}