Last active
January 11, 2018 13:52
-
-
Save soulduse/3661e831ca19f3a22eea863fb7c9e248 to your computer and use it in GitHub Desktop.
Dialog Helper with Kotlin
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
/** | |
* ex) | |
* CustomDialog | |
* .create { | |
* with { mContext } | |
* items { | |
* CustomDialog.Items().apply { | |
* message = "This is dialog message" | |
* positiveTitle = "Positive title" | |
* negativeTitle = "Negative title" | |
* } | |
* } | |
* listener({ | |
* // do positive something | |
* },{ | |
* // do negative something | |
* }) | |
* } | |
*/ | |
class CustomDialog private constructor( | |
private val mContext: Context, | |
private val items: Items, | |
private val positive: ()-> Unit, | |
private val negative: (()-> Unit)? = null){ | |
private constructor(builder: Builder): this(builder.context, builder.items, builder.positive, builder.negative) | |
private fun show() = AlertDialog.Builder(mContext).apply { | |
with(items){ | |
setMessage(message) | |
setPositiveButton(positiveTitle, { _, _ -> | |
positive() | |
}) | |
negative?.let{ | |
setNegativeButton(negativeTitle, { dialog, _ -> | |
dialog.dismiss() | |
negative?.invoke() | |
}) | |
} | |
} | |
}.create().show() | |
companion object { | |
fun create(init: Builder.() -> Unit) = Builder(init).build().show() | |
} | |
class Builder private constructor(){ | |
lateinit var context: Context | |
lateinit var items: Items | |
lateinit var positive: ()-> Unit | |
var negative: (()-> Unit)?= null | |
constructor(init: Builder.()-> Unit): this(){ | |
init() | |
} | |
fun with(init: Builder.() -> Context) = apply { context = init() } | |
fun items(init: Builder.() -> Items) = apply { items = init() } | |
fun listener(pos: () -> Unit, neg: (()-> Unit)? = null) = apply { | |
positive = pos | |
neg?.let { negative = neg } | |
} | |
fun build() = CustomDialogE(this) | |
} | |
class Items { | |
lateinit var message: String | |
lateinit var positiveTitle: String | |
lateinit var negativeTitle: String | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment