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);
}