如何以编程方式删除AlertDialog

Nad*_*dir 2 android android-alertdialog

在Android应用程序中,我向用户显示没有按钮的AlertDialog,只显示一条消息.如何以编程方式销毁AlertDialog以使其不再可见?我尝试使用cancel()和dismiss(),但它们不工作,视图仍然存在.

AlertDialog.Builder test = new AlertDialog.Builder(context);
test.setTitle("title");
test.setCancelable(true);
test.setMessage("message...");
test.create().show();
Run Code Online (Sandbox Code Playgroud)

然后我试了

test.show().cancel()

test.show().dismiss()
Run Code Online (Sandbox Code Playgroud)

但没有工作.

tin*_*k90 13

您应该参考AlertDialog本身,而不是构建器.

AlertDialog.Builder test = new AlertDialog.Builder(context);
test.setTitle("title");
test.setCancelable(true);
test.setMessage("message...");
ALertDialog testDialog = test.create();
testDialog.show();  // to show
testDialog.dismiss();  // to dismiss
Run Code Online (Sandbox Code Playgroud)


azi*_*ian 5

AlertDialog.Builder test = new AlertDialog.Builder(context);
...

AlertDialog dialog = test.create().show();
Run Code Online (Sandbox Code Playgroud)

以后你想隐藏它:

 dialog.dismiss();
Run Code Online (Sandbox Code Playgroud)