AlertDialog关闭不起作用

问题描述:

我有以下AlertDialog:

I have the following AlertDialog:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle(R.string.title);
dialogBuilder.setMessage(mContext.getString(R.string.message));
dialogBuilder.setPositiveButton(R.string.positive, new MyOnClickListener());
dialogBuilder.setNegativeButton(R.string.negative, new MyOnClickListener());
dialogBuilder.show();

使用此ClickListener

with this ClickListener

public static class MyOnClickListener implements DialogInterface.OnClickListener{
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
    }
  }

我希望当单击两个按钮中的任何一个时,该对话框都将关闭,但该对话框保持打开状态.

I would expect the dialog to be closed, when clicking on either of the buttons, but the dialog stays open instead.

我调试了onClick方法和该行

I debugged the onClick method and the line

dialog.dismiss() 

正在执行,但是什么也没有发生.

is being executed, but nothing happens.

我要去哪里错了,或者该如何解决?

Where am I going wrong or how can I fix this?

在顶部声明您的AlertDialog,例如:

Declare your AlertDialog at the top like:

private AlertDialog myAlertdialog;

而不是将您的dialogBuilder.show();替换为

myAlertDialog = dialogBuilder.create();
myAlertDialog.show();

比您可以致电myAlertDialog.dismiss();