Skip to content

Instantly share code, notes, and snippets.

@Marchuck
Created October 11, 2019 11:18
Show Gist options
  • Save Marchuck/702138750218aac5548f3bf4877111fd to your computer and use it in GitHub Desktop.
Save Marchuck/702138750218aac5548f3bf4877111fd to your computer and use it in GitHub Desktop.
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