Android onDismissListener调用了Cancel

时间:2017-03-25 14:54:19

标签: java android alertdialog event-listener

我在AlertDialog中添加了AlertDialog.OnDismissListener。调用dialog.cancel()时,会调用onCancelListener以及onDismissListener

这是预期的行为吗?我可以以某种方式阻止在调用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!

3 个答案:

答案 0 :(得分:1)

没有理由同时使用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的侦听器中按下取消时要运行的代码:

.setNegativeButton(R.string.cancel, (d, i) -> {
                    // Your code that reacts to the user pressing "Cancel" goes here!
                    Log.d(TAG, "Cancel pressed!");
                })

答案 1 :(得分:0)

您无需在setPositiveButton / setNegativeButton回调中调用dismiss或cancel,因此您可以直接在那里实现逻辑。

答案 2 :(得分:0)

不要使用OnCancelListenerOnDismissListener作为区分消极和积极按钮点击的方法。

您可以为自己的侦听器中的每个按钮实现逻辑,而不是调用d.dismiss()d.cancel()