【问题标题】:Closing alert dialog in android on press of button for first time第一次按下按钮时关闭android中的警报对话框
【发布时间】:2014-12-20 14:25:13
【问题描述】:

我在做什么:

  • 我正在使用以下代码启动一个对话框
  • 点击我想关闭对话框

发生了什么;

  • 对话框正在关闭,但我必须单击两次确定按钮(看起来警报弹出两次,但我第二次按确定关闭)

我想做什么:

  • 我想在第一次点击确定时关闭对话框

   public void open(String custMsg){

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setMessage(custMsg);
    alert.setCancelable(false);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {

        dialog.cancel();
      }
    });
    alert.show();

}

【问题讨论】:

  • 打电话给dialog.dismiss()而不是dialog.cancel();
  • 我试过但结果相同!....正如我所说,对话框将关闭,但如果弹出两次看起来像对话框本身......
  • 在您打开对话框的位置显示该事件..
  • 在 onResume() 中我弹出了这个警告对话框
  • 好吧,这就是问题所在。因为每次在您的活动中,您的 onResume() 都会调用并弹出。

标签: android android-alertdialog


【解决方案1】:

您不需要在onResume() 中弹出对话框。每次再次聚焦窗口时都会调用onResume()。当对话框弹出时,窗口失去焦点。当您取消对话框时,Activity 再次获得焦点,onResume() 被执行并再次显示对话框。

在其他地方调用对话框,它会起作用(例如onStart()

【讨论】:

  • 解决了这个问题,但是看看这个问题 stackoverflow.com/q/27577887/1083093(类似于现在的行为)
【解决方案2】:

简单的解决方案是。

您必须将打开弹出窗口的代码移动到某个位置,因为无论何时输入您的活动,您的onResume() 都会被调用,并且每次弹出对话框都会打开,这是错误的。因此,只需将该代码移到正确执行的地方即可。

注意:请致电 dialog.dismiss() 而不是 dialog.cancel();

【讨论】:

  • [+1] ... 解决了这个问题,但是看看这个问题 stackoverflow.com/q/27577887/1083093(类似于现在的行为)
【解决方案3】:

试试这个更好

public AlertDialog open(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this,
                AlertDialog.THEME_DEVICE_DEFAULT_DARK);
        builder.setTitle(R.string.about_title)
                .setMessage(msg)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).show();

        return builder.create();
    }

    }

但您还需要创建对话框,我看不到您创建它的位置

【讨论】:

  • 如果您检查上面的 cmets,那么您可以看到谁说了什么,什么不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
相关资源
最近更新 更多