Last active
September 10, 2018 09:49
-
-
Save Lamartio/85b81dc5ffef296db1fe30513e7fc0e6 to your computer and use it in GitHub Desktop.
Kotlin's simple layout trick
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
LinearLayout(this).apply { | |
orientation = LinearLayout.VERTICAL | |
addView(TextView(context).apply { | |
text = "Hello" | |
}) | |
addView(TextView(context).apply { | |
text = "click me" | |
setOnClickListener { | |
// ... | |
} | |
}) | |
} |
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
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) | |
} |
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
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) | |
} |
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
LinearLayout(this) layout { | |
+textView { | |
text = "Hello" | |
} | |
} | |
val Layout<*>.textView: TextView get() = TextView(context) | |
val Layout<*>.button: Button get() = Button(context) |
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
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