2

例如,如果我们正在构建一个自定义视图,如下所示:

class FrameLayoutNormal: FrameLayout{
constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

    textView{
         lparams(...)
    }
}

我们不能定义 lparams,因为编译器不知道父级是谁。如果我们将 textView 包装在 FrameLayout 中,它就可以工作,并且您可以指定布局参数。但是在自定义视图中,父级就是它自己。那么我们如何让孩子们意识到这一点,以便我们可以使用扩展程序呢?

除了从以下位置扩展之外,还有什么方法可以让它工作_FrameLayout

4

1 回答 1

0

一个老问题,但因为它很常见......应用来自https://github.com/Kotlin/anko/issues/267的答案

我想你可能想要这样的东西:

class FrameLayoutNormal: AnkoComponent<Context> {
    override fun createView(ui: AnkoContext<Context>): View {
        return with(ui) {
            frameLayout {
                textView("Hello") {
                }.lparams()
            }
        }
    }
}

inline fun ViewManager.frameLayoutNormal(theme: Int = 0) = frameLayoutNormal(theme) {}
inline fun ViewManager.frameLayoutNormal(theme: Int = 0, init: View.(frameLayoutNormal: FrameLayoutNormal) -> Unit): View {
    val fln = FrameLayoutNormal()
    return ankoView({ fln.createView(AnkoContext.create(it))}, theme, {init(fln)})
}

这允许组件在 ANKO DSL 中使用。这种方法的一个缺点是自定义组件是 View,而不是 ViewGroup,因此不能在其定义之外添加其他子组件。制作一个可以在 ANKO DSL 中使用的 ViewGroup 的自定义组件是具有挑战性/费力的(如果我理解正确的话)。

于 2018-08-31T11:46:30.493 回答