Last active
July 11, 2021 22:11
-
-
Save RahulSDeshpande/20da9f6d7a56a3198465414da3a4c300 to your computer and use it in GitHub Desktop.
Kotlin Extension for the MaterialAlertDialog!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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