Android Prevent Dialog/AlertDialog Closed On Button Click

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

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.