Skip to content

Instantly share code, notes, and snippets.

@polson
Created August 17, 2020 21:27
Show Gist options
  • Save polson/cf7077c57d8dd7dc94efd1fc95c9695c to your computer and use it in GitHub Desktop.
Save polson/cf7077c57d8dd7dc94efd1fc95c9695c to your computer and use it in GitHub Desktop.
class BetterDialog<T> : DialogFragment() {
companion object {
val KEY_ARGS = "KEY_ARGS"
val KEY_CALLED_FROM_FRAGMENT = "KEY_CALLED_FROM_FRAGMENT"
val TAG = "DIALOG_TAG"
}
@Suppress("UNCHECKED_CAST")
private val args: DialogBuilderImpl.DialogArgs<T> by lazy {
checkNotNull(arguments?.getSerializable(KEY_ARGS) as DialogBuilderImpl.DialogArgs<T>) { "Args are null!" }
}
private val isCalledFromFragment by lazy {
checkNotNull(arguments?.getBoolean(KEY_CALLED_FROM_FRAGMENT)) { "Args are null!" }
}
@Suppress("UNCHECKED_CAST")
private fun getParent(): T {
return if (isCalledFromFragment) {
parentFragment as T
} else {
activity as T
}
}
@NonNull
@Suppress("UNCHECKED_CAST")
override fun onCreateDialog(@Nullable savedInstanceState: Bundle?): Dialog {
val context: Context =
checkNotNull(activity) { "Unable to show dialog, activity is null!" }
args.run {
val b = AlertDialog.Builder(context)
title?.let { b.setTitle(it) }
message?.let { b.setMessage(it) }
yesButtonAction?.let {
b.setPositiveButton(yesButtonText) { _, _ ->
(it as DialogCallback<T>).invoke(
getParent()
)
}
}
noButtonAction?.let {
b.setNegativeButton(noButtonText) { _, _ ->
(it as DialogCallback<T>).invoke(
getParent()
)
}
}
return b.create()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment