我想创建一个自定义视图,这只是一些Android视图的包装。我考虑创建一个自定义ViewGroup来管理它的子视图的布局,但我不需要这么复杂。我要做的基本上是这样的:
class MainActivity
verticalLayout {
textView {
text = "Something that comes above the swipe"
}
swipeLayout {
}
}
class SwipeLayout
linearLayout {
textView {
text = "Some text"
}
textView {
text = "Another text"
}
}
原因是我想移动的SwipeLayout代码到一个单独的文件,但不想做任何复杂的布局自己的东西。使用Anko可以实现这一点吗?
编辑:如建议,是否有可能重用Kotlin Anko的布局解决了这个问题,如果视图是根布局。但如示例所示,我想将其包含在另一个布局中。这可能吗?
你可以使用ViewManager
fun ViewManager.swipeLayout() = linearLayout {
textView {
text = "Some text"
}
textView {
text = "Another text"
}
}
class MainActivity
verticalLayout {
textView {
text = "Something that comes above the swipe"
}
swipeLayout {}
}
我也在寻找这样的东西,但我发现自定义视图的最优解决方案是这样的:
public inline fun ViewManager.customLayout(theme: Int = 0) = customLayout(theme) {}
public inline fun ViewManager.customLayout(theme: Int = 0, init: CustomLayout.() -> Unit) = ankoView({ CustomLayout(it) }, theme, init)
class CustomLayout(c: Context) : LinearLayout(c) {
init {
addView(textView("Some text"))
addView(textView("Other text"))
}
}