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

Suh*_*ain 12 android kotlin anko

我想创建一个自定义视图,它只是一些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"
  }
}
Run Code Online (Sandbox Code Playgroud)

原因是我想将SwipeLayout代码移动到一个单独的文件中,但不希望自己做任何复杂的布局.这可能使用Anko吗?

编辑:正如所建议的,如果视图是根布局,是否可以在Kotlin Anko中重用布局来解决此问题.但是如示例所示,我想将其包含在另一个布局中.那可能吗?

sun*_*lee 6

你可以使用ViewManager.

fun ViewManager.swipeLayout() = linearLayout {
  textView {
    text = "Some text"
  }
  textView {
    text = "Another text"
  }
}
Run Code Online (Sandbox Code Playgroud)
class MainActivity
  verticalLayout {
    textView {
      text = "Something that comes above the swipe"
    }
    swipeLayout {}
}
Run Code Online (Sandbox Code Playgroud)


小智 3

我也在寻找类似的东西,但我找到的自定义视图的最佳解决方案是这样的:

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"))
    }
}
Run Code Online (Sandbox Code Playgroud)