Android:如何在点击“确定”按钮后使AlertDialog消失?

3

我正在询问以下链接中已经提出的同样的问题,但是这些链接中提出的解决方案对我来说不起作用,因此我再次发布它。

如何使AlertDialog消失?

Android AlertDialog在单击“确定”按钮时总是退出

用户单击AlertDialog OK按钮后如何导航到下一个活动?

基本上,我正在创建一个AlertDialog构建器,以通知用户要求启用使用数据访问的设置,并且当按下OK按钮时,设置菜单将打开。当我按返回按钮返回应用程序时,虽然我希望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;

}

任何提示,这里可能出了什么问题?
1个回答

3

测试后编辑:

我在6.0.1上测试了OP的代码,结果如预期 - 即点击“OK”后对话框被关闭。我将保留我的初始答案作为另一种可行的替代方案。其他替代方案可以在这里找到。


您可以从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 7.0手机上运行此代码,并尝试了您链接中发布的其他建议,但没有运气。 - Pagar
@Pagar 在对话框被关闭后或从设置返回时,show_alert方法是否再次被调用? - Trevor Halvorson
抱歉造成困惑,现在它已经正常工作了。在仔细查看我的代码时,我发现调用顺序中存在一些同步问题。感谢您的帮助! - Pagar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接