Skip to content

Instantly share code, notes, and snippets.

@Lamartio
Last active September 10, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lamartio/85b81dc5ffef296db1fe30513e7fc0e6 to your computer and use it in GitHub Desktop.
Save Lamartio/85b81dc5ffef296db1fe30513e7fc0e6 to your computer and use it in GitHub Desktop.
Kotlin's simple layout trick
LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
addView(TextView(context).apply {
text = "Hello"
})
addView(TextView(context).apply {
text = "click me"
setOnClickListener {
// ...
}
})
}
LinearLayout(this) layout {
+TextView(context) {
}
}
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {
// ...
operator fun <V : View> V.invoke(block: V.() -> Unit): V =
also(block)
}
LinearLayout(this) layout {
+TextView(context)
}
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {
val context = layout.context
operator fun <V : View> V.unaryPlus(): V =
also(layout::addView)
}
LinearLayout(this) layout {
+textView {
text = "Hello"
}
}
val Layout<*>.textView: TextView get() = TextView(context)
val Layout<*>.button: Button get() = Button(context)
LinearLayout(this) layout {
// ...
}
infix fun <V : ViewGroup> V.layout(block: Layout<V>.() -> Unit): V =
also { Layout(it).run(block) }
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment