在Anko DSL中创建一个自定义View / ViewGroup类

我想创建一个自定义的视图,这只是一些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")) } }