我在AlertDialog中添加了一个AlertDialog.OnDismissListener。当调用dialog.cancel()时,将调用onCancelListeneronDismissListener
这是预期的行为吗?当调用onDismissListener而不是dialog.cancel()时,我能防止调用dialog.dismiss()吗?
有一些代码:

AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setView(view)
                .setTitle(title)
                .setIcon(icon)
                .setCancelable(true)
                .setNegativeButton(R.string.cancel, (d, i) -> {
                    d.cancel();
                    Log.d(TAG, "Cancel pressed!");
                })
                .setPositiveButton(positiveBtnText, (d, i) -> {
                    d.dismiss();
                    Log.d(TAG, "Dismiss pressed!");
                });
        AlertDialog dialog = builder.create();
        dialog.setOnCancelListener(dialogInterface -> {
            Log.d(TAG, "Dialog canceled!");
        });
        dialog.setOnDismissListener(dialogInterface -> {
            Log.d(TAG, "Dialog dismissed!");
        });

意外行为也会出现在日志中:
03-25 05:15:31.895 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Cancel pressed!
03-25 05:15:31.895 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Operation canceled!
03-25 05:15:31.896 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Dismiss called!

最佳答案

没有理由同时使用setNegativeButton/setPositiveButton和设置OnCancelListener/OnDismissListener
删除:

dialog.setOnCancelListener(dialogInterface -> {
            Log.d(TAG, "Dialog canceled!");
        });
        dialog.setOnDismissListener(dialogInterface -> {
            Log.d(TAG, "Dialog dismissed!");
        });

并添加当用户在提供给setPositiveButton的侦听器中按ok时要运行的代码:
// ...
.setPositiveButton(positiveBtnText, (d, i) -> {
                    // Your code that reacts to the user pressing "OK" goes here!
                    Log.d(TAG, "Dismiss pressed!");
                });

类似地,添加当用户在提供给setNegativeButton的侦听器中按cancel时要运行的代码:
.setNegativeButton(R.string.cancel, (d, i) -> {
                    // Your code that reacts to the user pressing "Cancel" goes here!
                    Log.d(TAG, "Cancel pressed!");
                })

10-05 22:50