【问题标题】:Android: How to make AlertDialog disappear on clicking ok button?Android:如何使 AlertDialog 在单击确定按钮时消失?
【发布时间】:2017-11-29 20:48:36
【问题描述】:

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

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;

}

任何提示可能会出现什么问题?

【问题讨论】:

    标签: android android-alertdialog


    【解决方案1】:

    经过一些测试后编辑

    我在 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 7.0 手机上运行此代码,我也尝试了您链接中发布的其他建议,但没有运气。
    • @Pagar 在对话框关闭或从设置返回后是否再次调用show_alert 方法?
    • 很抱歉造成混乱,它现在可以工作了,我在仔细查看我的代码时发现调用序列中存在一些同步问题。感谢您的帮助!
    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2022-07-24
    • 2016-09-26
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多