Skip to content

Instantly share code, notes, and snippets.

@RahulSDeshpande
Last active July 11, 2021 22:11
Show Gist options
  • Save RahulSDeshpande/20da9f6d7a56a3198465414da3a4c300 to your computer and use it in GitHub Desktop.
Save RahulSDeshpande/20da9f6d7a56a3198465414da3a4c300 to your computer and use it in GitHub Desktop.
Kotlin Extension for the MaterialAlertDialog!
// Kotlin extension
fun Context.alert(
@StyleRes style: Int = 0,
dialogBuilder: MaterialAlertDialogBuilder.() -> Unit
) {
MaterialAlertDialogBuilder(this, style)
.apply {
setCancelable(false)
dialogBuilder()
create()
show()
}
}
fun MaterialAlertDialogBuilder.negativeButton(
text: String = "No",
handleClick: (dialogInterface: DialogInterface) -> Unit = { it.dismiss() }
) {
this.setNegativeButton(text) { dialogInterface, _ -> handleClick(dialogInterface) }
}
fun MaterialAlertDialogBuilder.positiveButton(
text: String = "Yes",
handleClick: (dialogInterface: DialogInterface) -> Unit = { it.dismiss() }
) {
this.setPositiveButton(text) { dialogInterface, _ -> handleClick(dialogInterface) }
}
fun MaterialAlertDialogBuilder.neutralButton(
text: String = "OK",
handleClick: (dialogInterface: DialogInterface) -> Unit = { it.dismiss() }
) {
this.setNeutralButton(text) { dialogInterface, _ -> handleClick(dialogInterface) }
}
// Usage
alert {
setTitle("Confirm")
setMessage("Are you sure you want to delete this item?")
positiveButton { // Do something }
negativeButton { // Do something }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment