代码之家  ›  专栏  ›  技术社区  ›  theblitz

在Korlin的自定义视图中访问属性

  •  0
  • theblitz  · 技术社区  · 6 年前

    我正在Kotlin中创建一个自定义视图。

    对于施工人员,我遵循以下建议: https://blog.q42.nl/the-danger-of-assumptions-kotlin-with-android-custom-views-adb79bf2da45

    我的问题是,现在init块无法识别attrs参数,因为它们不在主构造函数中。

    我错过什么了吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Onik    6 年前

    只需使用实体构造构造函数,并从内部调用初始化属性的函数。

    例如:

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        attrs?.let { initAttrs(it) }
    }
    
    private fun initAttrs(attrs: AttributeSet) {
        ...
    }