第一次按下按钮时如何关闭安卓中的警告对话框

4

我正在做什么:

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

发生了什么事情:

  • 对话框正在关闭,但我必须点击两次“确定”按钮(看起来像是弹出了两次警告,但第二次按下“确定”时关闭)

我想要做的:

  • 我希望在第一次点击“确定”时关闭对话框

   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();

}

1
请调用 dialog.dismiss() 而不是 dialog.cancel(); - RockStar
我尝试了,但结果一样!就像我说的那样,对话框会关闭,但似乎对话框本身弹出了两次...... - Devrath
在onResume()中,我正在弹出此警报对话框。 - Devrath
3
好的,这就是问题所在。因为每次你处于活动状态时,你的onResume()方法都会被调用并弹出窗口。 - RockStar
你可能在onCreate()和onResume()方法中调用了dialog两次,需要检查并在onResume()方法中移除其中一个。 - W I Z A R D
显示剩余4条评论
3个回答

4
您无需在 onResume() 中弹出对话框。每次窗口重新获得焦点时,都会调用 onResume()。当对话框弹出时,窗口失去了焦点。当您取消对话框后,活动再次获得了焦点,并执行 onResume() 并再次显示对话框。

在其他地方调用对话框即可使其正常工作(例如,在 onStart() 中)。


已解决,但请看一下这个问题 stackoverflow.com/q/27577887/1083093(类似于当前行为) - Devrath

2

简单的解决方案是。

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

注意:调用dialog.dismiss()而不是dialog.cancel();


[+1] ... 已解决,但请看一下这个问题stackoverflow.com/q/27577887/1083093(类似于当前的行为) - Devrath

0

试试这个更好的方法

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();
    }

    }

但你还需要创建对话框,我看不到你在哪里创建它


如果您查看上面的评论,就可以看到是谁说了什么以及哪些内容无法正常工作。 - RockStar

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