[解决问题系] DialogFragment can not be attached to a container view

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时,并没有重新创建视图,而DialogFragmnetonActivityCreated时判断视图是否有Parent。而因为原来的contentView对象没有被销毁,通过它getParent是不为null,所以抛出了此异常。

解决方式1

将contentView放在局部变量。

解决方式2.

// 先调用一下父类方法(因为恒返回空,就不会存在问题)
contentView = super.onCreateView(inflater, container, savedInstanceState);
if (contentView == null) {
   contentView = inflater.inflate(getLayoutId(), container, false);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值