DialogFragment 是Google官方比较推荐的一种弹框确认交互方式,因为它可以保存生命周期状态,一般我们会extends DialogFragment
像下面这种写法
在onCreateView中初始化视图,然后绑定控件
运行-第一次没问题,有时候点击或者隐藏会抛出一个异常:
java.lang.IllegalStateException: DialogFragment can not be attached to a container view
意思就是说这个view 以及被包含添加了,重复添加会报错
Fragment中也有类似的坑,所以,搞懂原理就可以知道如何避免了,
首先判断下根view是否添加:
rootView = super.onCreateView(inflater,container,savedInstanceState);
if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_exit,container,false); this.tv_yes = rootView.findViewById(R.id.tv_dialog_yes); this.tv_no = rootView.findViewById(R.id.tv_dialog_no); }
完整代码:
package com.android.angola.wenna.plus.ui.Fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.angola.wenna.R; public class ExitFragment extends DialogFragment { private View rootView; private TextView tv_yes; private TextView tv_no; private OnYesClickListener onYesClickListener; private onNoClickListener onNoClickListener; public void setOnNoClickListener(ExitFragment.onNoClickListener onNoClickListener) { this.onNoClickListener = onNoClickListener; } public void setOnYesClickListener(OnYesClickListener onYesClickListener) { this.onYesClickListener = onYesClickListener; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { rootView = super.onCreateView(inflater,container,savedInstanceState); if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_exit,container,false); this.tv_yes = rootView.findViewById(R.id.tv_dialog_yes); this.tv_no = rootView.findViewById(R.id.tv_dialog_no); } return rootView; } public interface OnYesClickListener{ void onYesClickener(); } public interface onNoClickListener{ void onNoClicked(); } @Override public void onResume() { super.onResume(); this.tv_yes.setOnClickListener(v -> onYesClicked()); this.tv_no.setOnClickListener(v -> onNoClicked()); } private void onNoClicked() { if (onNoClickListener != null) { onNoClickListener.onNoClicked(); } } private void onYesClicked() { if (onYesClickListener != null) { onYesClickListener.onYesClickener(); } } }