android - 从 onpause 中关闭警报对话框生成器

标签 android

我正在使用以下代码来显示带有两个按钮的警告对话框。但是,如果在 Activity 暂停时对话框未被取消,则会引发错误。我知道您可以使用 .dismiss 关闭对话框,但这是一个 AlertDialog Builder 而不是对话框。知道如何做到这一点吗?

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this);

                // Setting Dialog Title
                alertDialog.setTitle("Title");

                // Setting Dialog Message
                alertDialog.setMessage("Message");

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        //yes
                        dialog.cancel();

                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //no                
                    dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();

最佳答案

显示对话框时可以得到AlertDialog:

dialog = alertDialog.show(); // show and return the dialog

然后在 onPause 中你可以关闭 AlertDialog:

@Override
protected void onPause() {
    super.onPause();
    if (dialog != null) {
        dialog.dismiss();
    }
}

对话框需要定义为实例变量才能工作:

私有(private) AlertDialog 对话框;//实例变量

顺便说一句,AlertDialog.Builder 是一个构建器,因为您可以使用 builder pattern像这样:

dialog = AlertDialog.Builder(MyActivity.this)
    .setTitle("Title");
    .setMessage("Message")
[...]
    .show();

关于android - 从 onpause 中关闭警报对话框生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139428/

相关文章:

java - 如何将多个功能添加到一个命令中?

android - 条码扫描 是否有用于获取产品详细信息等的 API?

android - 获取应用程序的资源语言

android - 如何防止 Android Telnet 客户端 session 丢失

android - 如何在 Android 中使用 XQuery 从 XML 文件中查询数据

android - 我卡在我的 Android 程序上了

android - 如何使用 ARCore Camera 拍摄带有物体的图像?

java - Android Realm : Many to Many Relationship

android - 使用 Chrome 自定义标签发布数据

android - 在 Android 中发送一条未知字符替换为 "replacement character"的短信 (UTF-16)