我在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!
答案 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)
不要使用OnCancelListener
和OnDismissListener
作为区分消极和积极按钮点击的方法。
您可以为自己的侦听器中的每个按钮实现逻辑,而不是调用d.dismiss()
和d.cancel()
。