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 中重用布局解决了这个问题。但如示例中所示,我想将其包含在另一个布局中。那可能吗?

4

2 回答 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 {}
}
于 2016-12-14T02:38:20.453 回答
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"))
    }
}
于 2016-12-05T10:21:10.783 回答