Android Prevent Dialog/AlertDialog Closed On Button Click

April 21, 2018

The following example won’t close dialog when positive/ok button is clicked unless dialog.dismiss is called.

val view = activity.layoutInflater.inflate(R.layout.dialog_generic_value, null)

val builder = AlertDialog.Builder(context)
        .setTitle("Password Hint")
        .setMessage("Use a hint only you would understand.")
        .setView(view)
        .setPositiveButton(android.R.string.ok, null)
        .setNegativeButton(android.R.string.cancel) { dialog, whichButton ->
            // so something, or not - dialog will close
        }
val dialog = builder.create()

dialog.setOnShowListener {
    val okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
    okButton.setOnClickListener {
        // dialog won't close by default
        dialog.dismiss()
    }
}

dialog.show()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.