我如何 return 来自 AlertDialog 的布尔值?
How can I return a Boolean from AlertDialog?
在下面的代码中,它 returns 立即为真并忽略 AlertDialog 的结果...
我正在尝试创建一个函数来生成 returns 布尔值的 AlertDialogs,并且我想在程序的其他地方使用该函数。
fun showTwoButtonDialog(
theContext: Context,
theTitle: String = "Yes or no?",
theMessage: String,
): Boolean {
var a = true
AlertDialog.Builder(theContext)
.setTitle(theTitle)
.setMessage(theMessage)
.setPositiveButton("Yes") { _, _ ->
a = true
}
.setNegativeButton("No") { _, _ ->
a = false
}.show()
return a
}
你可以为此使用函数
fun showTwoButtonDialog(
theContext: Context,
theTitle: String = "Yes or no?",
theMessage: String,
resultBoolean: (Boolean) -> Unit
) {
AlertDialog.Builder(theContext)
.setTitle(theTitle)
.setMessage(theMessage)
.setPositiveButton("Yes") { _, _ ->
resultBoolean(true)
}
.setNegativeButton("No") { _, _ ->
resultBoolean(false)
}.show()
}
函数调用
showTwoButtonDialog(this,"Title","Message") { result->
if(result){
//Do whatever with result
}
}
在下面的代码中,它 returns 立即为真并忽略 AlertDialog 的结果...
我正在尝试创建一个函数来生成 returns 布尔值的 AlertDialogs,并且我想在程序的其他地方使用该函数。
fun showTwoButtonDialog(
theContext: Context,
theTitle: String = "Yes or no?",
theMessage: String,
): Boolean {
var a = true
AlertDialog.Builder(theContext)
.setTitle(theTitle)
.setMessage(theMessage)
.setPositiveButton("Yes") { _, _ ->
a = true
}
.setNegativeButton("No") { _, _ ->
a = false
}.show()
return a
}
你可以为此使用函数
fun showTwoButtonDialog(
theContext: Context,
theTitle: String = "Yes or no?",
theMessage: String,
resultBoolean: (Boolean) -> Unit
) {
AlertDialog.Builder(theContext)
.setTitle(theTitle)
.setMessage(theMessage)
.setPositiveButton("Yes") { _, _ ->
resultBoolean(true)
}
.setNegativeButton("No") { _, _ ->
resultBoolean(false)
}.show()
}
函数调用
showTwoButtonDialog(this,"Title","Message") { result->
if(result){
//Do whatever with result
}
}