Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AlertDialog.kt
fun Fragment.createAlertDialog() =
AlertDialog.Builder(ContextThemeWrapper(context, R.style.custom_dialog_style))
data class DialogAction(
var text: String,
var onClick: (() -> Unit)? = null
)
data class AlertDialogData(
val cancellable: Boolean,
var title: String = "", var message: String = "",
var positiveAction: (DialogAction.() -> Unit)? = null,
var negativeAction: (DialogAction.() -> Unit)? = null,
var neutralAction: (DialogAction.() -> Unit)? = null
)
/**
* simple DSL for creating alert dialogs
*/
fun Fragment.alertDialog(
cancellable: Boolean = true,
init: AlertDialogData.() -> Unit
): AlertDialog {
val alertDialogData = AlertDialogData(cancellable)
alertDialogData.init()
val builder = createAlertDialog()
.setTitle(alertDialogData.title)
.setMessage(alertDialogData.message)
alertDialogData.positiveAction?.let { body ->
val action = DialogAction("")
body(action)
builder.setPositiveButton(action.text) { _, _ ->
action.onClick?.invoke()
}
}
alertDialogData.negativeAction?.let { body ->
val action = DialogAction("")
body(action)
builder.setNegativeButton(action.text) { _, _ ->
action.onClick?.invoke()
}
}
alertDialogData.neutralAction?.let { body ->
val action = DialogAction("")
body(action)
builder.setNeutralButton(action.text) { _, _ ->
action.onClick?.invoke()
}
}
return builder.create()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment