Android:如何使 AlertDialog 在单击确定按钮时消失?

标签 android android-alertdialog

我在下面的链接中提出了与之前提出的相同问题,但这些链接中提出的解决方案对我不起作用,所以我再次发布。

How to make an AlertDialog disappear?

Android AlertDialog always exits when I click on OK Button

How to navigate to next activity after user clicks on AlertDialog OK button?

基本上,我正在创建一个 AlertDialog 构建器来通知用户要求启用使用数据访问的设置,当按下“确定”按钮时,“设置”菜单将打开。当我按下后退按钮返回应用程序时,AlertDialog 仍然可用,尽管我预计会被解雇以返回我的应用程序。

    public void show_alert(){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("This application requires access to the Usage Stats Service. Please " +
                        "ensure that this is enabled in settings, then press the back button to continue ");
    builder.setCancelable(true);

    builder.setPositiveButton(
            "OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                    startActivity(intent);
                    dialog.dismiss();
                }
            });

    builder.show();
    return;

任何提示这里可能出了什么问题?

最佳答案

一些测试后编辑:

我在 6.0.1 上测试了 OPs 代码,它的行为符合预期——即在单击“确定”后对话框被关闭。我将在下面留下我的初步答案作为也有效的替代方案。可以找到其他替代品 here .


您可以从您的 builder.show() 方法中获取对您的警报对话框的引用:

mMyDialog = builder.show();

在您的onClick 方法中:

mMyDialog.dismiss();

完整示例:

AlertDialog mMyDialog; // declare AlertDialog
public void show_alert(){
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("This application requires access to the Usage Stats Service. Please " +
                    "ensure that this is enabled in settings, then press the back button to continue ");
  builder.setCancelable(true);

  builder.setPositiveButton(
        "OK",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {

                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                startActivity(intent);
                mMyDialog.dismiss(); // dismiss AlertDialog
            }
        });

  mMyDialog = builder.show(); // assign AlertDialog
  return;
}

关于Android:如何使 AlertDialog 在单击确定按钮时消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769433/

相关文章:

android - alertDialog 访问 onClick() 中的值

java - 如何将 jchararray 作为参数发送给 C 函数

java - android代码中的long和Long有什么区别?

android - session 'app' : error when trying to run app

android - 如何在警报对话框上有两个单选列表?

android - 应用程序新版本通知

android - 在 AlertDialog 中禁用肯定按钮

java.lang.NoClassDefFoundError : Failed resolution of: Lretrofit2/Retrofit$Builder;

android - Android SDK 更改后的 Eclipse 错误

java - 如何使我的 AlertDialog 标题居中?