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

12

我想创建一个自定义视图,它只是一些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中重用布局解决此问题。但是,如示例所示,我想在另一个布局内包含它。这可行吗?

3
可能是 Is it possible to reuse a layout in Kotlin Anko 的重复问题。 - miensol
1
我同意@miensol的看法。请参考此答案:https://dev59.com/1Jvga4cB1Zd3GeqP5a23#40078650 - Slav
1
对不起,这本应该没问题的。但是如果我不想让我的自定义视图成为根布局怎么办?就像我展示的例子中,它被包含在另一个布局中。当我尝试这样做时,我会得到一个 java.lang.IllegalStateException: View is already set: org.jetbrains.anko._LinearLayout{8bdb786 V.E...... ......I. 0,0-0,0} 的错误提示。 - Suhair Zain
2个回答

6
您可以使用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 {}
}

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"))
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接