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

时间:2017-06-26 22:12:49

标签: 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构建器来通知用户要求启用Usage Data Access的设置,当按下OK按钮时,将打开Settings菜单。当我按下后退按钮返回应用程序时,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 个答案:

答案 0 :(得分:3)

经过一些测试后修改

我在6.0.1上测试了OP代码并且它按预期运行 - 即单击“确定”后对话框被解除。我将在下面留下我的初步答案作为替代方案也有效。可以找到其他替代方案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;
}