如何关闭Android alertdialog

Eng*_*mex 38 android

我正在开发一个测验,我需要用户在继续之前回答所有问题.当用户没有回答所有问题时,我会显示一个简单的警报,告知他或她.问题是无论我做什么我都无法关闭alertdialog.为什么dialog.cancel不工作?`这是代码:

AlertDialog.Builder ad = new AlertDialog.Builder(this);  
ad.setTitle("Unanswered Questions");  
ad.setMessage("You have not answered all the questions.");   
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int id) {  
     dialog.cancel(); 
}  
});  
ad.show(); 
Run Code Online (Sandbox Code Playgroud)

Pow*_*tar 77

AlertDialog.Builder本身不包含dismiss()cancel()方法.

这是一个方便的类来帮助你创建一个对话框,其中DOES访问这些方法.

这是一个例子:

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

AlertDialog alert = builder.create();

alert.show();
Run Code Online (Sandbox Code Playgroud)

然后,您可以alert.cancel()在警报(而不是构建器)上调用该方法.

  • 当点击监听器仍在使用构建器构建时,如何在点击监听器上使用警报...请解释一下 (2认同)

use*_*412 29

尝试使用

dialog.dismiss()

而不是使用

dialog.cancel()

  • dismiss()不适用于AlertDialog,仅适用于常规对话框 (5认同)

Ben*_*ros 9

使用setNegative按钮,不需要正面按钮!我保证你会赢得x


dhu*_*981 8

把这一行放在OnCreate()

Context mcontext=this;    
Run Code Online (Sandbox Code Playgroud)

他们在下面的代码中使用这个变量

final AlertDialog.Builder alert = new AlertDialog.Builder(
                                mcontext);
                        alert.setTitle(title);
                        alert.setMessage(description);
                        alert.setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        dialog.cancel();
                                    }
                                });
                        alert.show();
Run Code Online (Sandbox Code Playgroud)

试试这段代码..它运行成功..


con*_*ish 5

AlertDialog.Builder ad = new AlertDialog.Builder(this);  
ad.setTitle("Unanswered Questions");  
ad.setMessage("You have not answered all the questions.");   
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int id) {  
     dialog.dismiss(); 
}  
});  
ad.show(); 
Run Code Online (Sandbox Code Playgroud)


sha*_*608 5

回复一个旧帖子,但希望有人可能会觉得这很有用。改为这样做

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();
Run Code Online (Sandbox Code Playgroud)

然后你可以继续做,

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