Anko Layout DSL:如何使用已有的布局?

时间:2018-03-29 00:16:11

标签: android kotlin anko

我的问题与constrainLayout { ... }具体相关,但由于Anko Layout并不关心它适用于每个Layout

我可以这样做:

// Could also be verticalLayout { ... } or any other Layout
constraintLayout {
    // some layout logic e.g.
    view {
        // ...
    }.lparams {
        // ...
    }
}

现在我遇到了问题,因为this DSL创建了一个新的ConstraintLayout,但我希望对现有的ConstraintLayout执行相同的逻辑操作。我正在搜索类似“dsl”函数的内容,但我在文档或其他任何地方都找不到任何内容。

ConstraintLayout(this).dsl {
    // ...
}

applyRecursively { ... }函数,由AnkoViewDslMarker标记的类使用,即在布局DSL中,但不标记“我已存在的ConstraintLayout”因此我无法使用任何DSL功能。

所以也许一个简单的解决方案是使用annotation class标记我的对象,但我怀疑这是否有效,因为我在使用XML,“我已经存在的ConstraintLayout”也来自。我希望有人知道如何与Anko这样做。否则我将不得不提出问题:)

2 个答案:

答案 0 :(得分:0)

它很可能是您需要的ankoView(...) { ... }函数,它允许您使用作为第一个参数传递的函数提供的任意视图,其方式与Anko支持的视图相同本身。

请在此处查看说明:Is it extensible?

鉴于您已有constraintLayout,您可以执行以下操作:

ankoView({ constraintLayout }) { 
    // Inner DSL scope for constraintLayout
}

答案 1 :(得分:0)

我解决了ConstraintLayout" lparams"通过创建扩展功能,我可以使用喜欢 DSL:

inline fun View.constraintLparams(width: Int, height: Int, init: LayoutParams.() -> Unit) {
    val layoutParams = LayoutParams(width, height)
    layoutParams.init()
    this.layoutParams = layoutParams
}