AlertDialog 弹出两次

AlertDialog poping up twice

我在其 on createview() 方法中有一个 fragment 我提出了一个条件,如果此条件为真,则显示 alertdialog 并单击其任何按钮,关闭对话框但单击对话框的按钮再次弹出对话框,这是我的条件和里面的 dialog:

 if(getUser().isFirstTimeLogin() && getUser().getReceivedRequests().size() > 0 && getUser().getReceivedRequests().get(0).getStatus() == 0){

        dialog = new AlertDialog.Builder(getActivity()).create();
        LayoutInflater layoutInflater = getLayoutInflater();
        View dialogView = layoutInflater.inflate(R.layout.anonymous_login_popup, null);
        TextView title = (TextView) dialogView.findViewById(R.id.title);
        TextView description = (TextView) dialogView.findViewById(R.id.tv_anonymous_dialog_content);
        TextView okBtn = (TextView) dialogView.findViewById(R.id.okBtn);
        TextView cancelBtn = (TextView) dialogView.findViewById(R.id.cancelBtn);
        title.setText("Pending Request");
        description.setText("Your Spouse request is pending");
        okBtn.setText("Accept");
        cancelBtn.setText("Reject");
        Typeface tf = FontManager.getTypeface(getActivity(), FontManager.VARELA_ROUND);
        FontManager.setContainerTypeface(dialogView, tf);
        dialog.setView(dialogView);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        dialog.show();
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();                   acceptRejectRequest(String.valueOf(getUser().getReceivedRequests().get(0).getId()), 1);
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();                    acceptRejectRequest(String.valueOf(getUser().getReceivedRequests().get(0).getId()),     2);
            }
        });

    }

我使用并为我完美工作的方式是定义一个 AlertDialog 而不是 AlertDialog.Builder 然后我显示 AlertDialog

这是我的代码:

AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.DialogTheme);
LayoutInflater inflater = LayoutInflater.from(this);
View contentView = inflater.inflate(R.layout.custom_layout , null);
builder.setView(contentView);
AlertDialog alert = builder.create();
...
//instead of builder.show()
alert.show();

然后在点击时使用 alert.dismiss();

总是调试你的代码看看代码是如何执行的,在这种情况下,代码 运行 两次并且对话框相互堆叠,所以关闭上面的对话框弹出它下面的对话框所以看起来对话框弹出多次:)

编码愉快!

就显示对话框而言,我总是在实用程序 class 中设置一个像 dialogIsDisplayed 这样的布尔值标志。每当有调用对话框的事件时,我都会在该标志为 false 时显示对话框。立即,即调用对话框后,此标志设置为 true.

在对话框中,在调用 dismiss() 之前,此标志设置为 false

这样可以防止创建重复对话框。