在下面的代碼中,它立即回傳 true 并忽略 AlertDialog 的結果...
我正在嘗試創建一個函式來生成回傳布林值的 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
}
uj5u.com熱心網友回復:
您可以為此使用功能
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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463592.html
下一篇:KotlinSpringBootGradle-創建名稱為“resourceHandlerMapping”的bean時出錯-未設定ServletContext
