Dialog 不会在按下按钮时触发关闭侦听器

Dialog doesn't trigger the dismiss listener on a button press

我想向用户显示一个确定取消对话框,我想知道用户是否按下了确定、取消,或者他是否选择通过单击屏幕上的其他地方或按后退按钮来关闭对话框。

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    final EditText input = new EditText(MainActivity.this);
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            // ok stuff
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            // cancel stuff
        }
    });
    builder.setOnDismissListener(new DialogInterface.OnDismissListener()
    {
        @Override
        public void onDismiss(DialogInterface dialog)
        {
            //dismiss stuff
        }
    });
    builder.show();

这里的问题是每当用户按下 ok 按钮时,关闭侦听器就会被正确触发 after.Is 如果用户按下按钮,有什么方法可以不触发关闭侦听器?

我知道我可以使用布尔标志,但我希望实际上有一个优雅的解决方案。

我不是在寻找有关如何防止对话被关闭的解决方案。我正在寻找有关如何防止在按下确定按钮并关闭对话框时触发关闭侦听器的解决方案。

setOnDismissListener() 将因 任何原因 被调用。这意味着如果对话框因 Ok/Cancel 按钮按下或屏幕触摸或后退按钮或主页按钮按下而从屏幕上消失,将调用 setOnDismissListener()

Sets the callback that will be called when the dialog is dismissed for any reason.

If you are interested in listening for all cases where the dialog is dismissed and not just when it is canceled, see setOnDismissListener

所以解决你提到的问题,使用一些布尔标志检查并处理它。

您可以尝试 CustomViewDialog 使用

LayoutInflater myDialog = getLayoutInflater();
        
View convertView = (View) myDialog.inflate(R.layout.MyLayoutXmlFile, null);

也不要使用 positivenegative 按钮,仅在对话框布局中使用按钮。

您可以在被关闭后再次显示该对话框!

我想你需要的是setOnCancelListener()