Android 如何在do while循环中连续显示AlertDialog,直到满足特定条件?
我有一个Android 如何在do while循环中连续显示AlertDialog,直到满足特定条件?,android,kotlin,android-alertdialog,do-while,Android,Kotlin,Android Alertdialog,Do While,我有一个AlertDialog,我想至少向用户显示一次,然后即使在用户单击“确定”后,也会持续向用户显示该对话框,直到满足特定条件为止 以下是迄今为止我为AlertDialog提供的代码结构: do { val dialogShow: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity) dialogShow.setCancelable(false) dialogShow.setMessage(&quo
AlertDialog
,我想至少向用户显示一次,然后即使在用户单击“确定”后,也会持续向用户显示该对话框,直到满足特定条件为止
以下是迄今为止我为AlertDialog提供的代码结构:
do {
val dialogShow: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity)
dialogShow.setCancelable(false)
dialogShow.setMessage("Message")
.setPositiveButton(
"ok",
object : DialogInterface.OnClickListener {
override fun onClick(dialogInterface: DialogInterface, i: Int) {
if (checkCondition()) {
conditionMet = true
} else {
// Keep looping
}
}
})
.setNegativeButton(
"cancel",
object : DialogInterface.OnClickListener {
override fun onClick(dialogInterface: DialogInterface, i: Int) {
conditionMet = true
return
}
})
dialogShow.show()
} while (conditionMet == false)
我现在面临的问题是,AlertDialog将显示一次,但再也不会显示。即使
conditionMet=false
它也不会继续显示。如何在循环中持续显示相同的AlertDialog
?通过将显示代码包装在循环中,可以连续显示它。如果对话框被取消,您可能希望执行的操作将重新显示该对话框。类似于这个伪代码:
fun showObtrusiveDialog() {
...
dialog.setPositiveButton {
if(shouldStillBeObtrusive()) showObtrusiveDialog()
...
}.setNegativeButton {
...
}
dialog.show()
}
另一种处理方法是禁用按钮,直到您准备好允许用户关闭对话框。当您的条件发生变化时,您可以调用以下扩展函数:
fun AlertDialog.setAllButtonsState(enabled: Boolean) {
arrayOf(DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE, DialogInterface.BUTTON_NEUTRAL)
.forEach { getButton(it)?.setEnabled(enabled) }
}
因此,您可以在显示它之前调用它以禁用它们,并在条件更改时再次调用它。您需要将对话框保留在一个属性中,这样您就可以从任何更改条件的地方访问它。我认为您实际上不希望将其放入循环中。否则,您只需每秒显示数千次对话框。您可能希望它在关闭后再次显示什么?@HenryTwist是的,但我希望它一直显示,直到
conditionMet
设置为true
。因此,我为什么要首先使用循环。那么你是说,conditionMet
是从其他地方更改的,而不是从你包含的代码更改的?@HenryTwist不,它不是从其他地方更改的。只有在我提供的代码中(在setPositiveButton
和setNegativeButton
中的if
语句),所以与其将其包装在循环中,不如将其包装在函数中并调用该函数?是的。然后,当它被取消时,您才再次显示它。实际上@TomDarious我以前的示例没有考虑按下后退按钮、他们在对话框外单击等。因此我更新了我的答案。您的新答案似乎没有考虑“肯定”和“否定”按钮。可以单击一次“否定”按钮并停止显示对话框。但是,在满足“肯定”按钮内的条件之前,“肯定”按钮可以显示多次。对不起,你是对的。我以为如果他们取消/取消,您仍然希望再次显示对话框。再次更新我的答案。每次用户单击“确定”或“取消”按钮时,我都需要检查条件。禁用它们将不允许出现这种情况。