【问题标题】:Kotlin Anko Custom View Parent scopeKotlin Anko 自定义视图父范围
【发布时间】:2016-11-28 10:41:46
【问题描述】:

如果我们正在构建一个自定义视图,例如,像这样:

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 扩展之外,还有什么方法可以让它工作?`

【问题讨论】:

  • 为什么不扩展_FrameLayout

标签: android kotlin anko


【解决方案1】:

一个老问题,但因为它很常见...... 应用来自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 的自定义组件是具有挑战性/费力的(如果我理解正确的话)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2016-06-09
    • 1970-01-01
    • 2021-05-08
    • 2022-08-09
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多