Home > Back-end >  How can I return a Boolean from AlertDialog?
How can I return a Boolean from AlertDialog?

Time:04-25

In the following code, it returns true immediately and ignores the result of AlertDialog...

I'm trying to make a function to produce AlertDialogs that returns a Boolean, and I want to use the function elsewhere in the program.

    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
    }


CodePudding user response:

You can use function for that

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()
}

function call

showTwoButtonDialog(this,"Title","Message") { result->
    if(result){
        //Do whatever with result
    }
}
  • Related