繁体   English   中英

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

[英]Create a custom View/ViewGroup class in Anko DSL

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM