当前位置:网站首页>[problem solving] dialogfragment can not be attached to a container view

[problem solving] dialogfragment can not be attached to a container view

2022-06-25 15:59:00 Favorite grapes

DialogFragment can not be attached to a container view

The whole story of the problem

In a DialogFragment in , Shows another Dialog, the other one Dialog Display time , Click OK to delete the current Dialog Show again

Pseudo code structure

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

problem

There is no problem with the first display , But when it shows MsgDialog, Click on Button Show again Dialog when , newspaper DialogFragment can not be attached to a container view.

reason

if (contentView == null) {
    
   contentView = inflater.inflate(getLayoutId(), container, false);
}

Show again Dialog when , No view is recreated , and DialogFragmnet stay onActivityCreated Judge whether the view has Parent. And because the original contentView The object has not been destroyed , Through it getParent Is not for null, So this exception is thrown .

Solution 1

take contentView Put it in a local variable .

Solution 2.

//  Call the parent method first ( Because constant return is empty , There will be no problem )
contentView = super.onCreateView(inflater, container, savedInstanceState);
if (contentView == null) {
   contentView = inflater.inflate(getLayoutId(), container, false);
}
原网站

版权声明
本文为[Favorite grapes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190538057396.html