我可以制作出色的Kotlin扩展功能吗?

时间:2019-07-14 18:12:13

标签: android kotlin kotlin-android-extensions kotlin-extension

这是我的代码

  theme?.let {
  ....
    titleText.setTextColor(it.pTextColor)
    contentText.setTextColor(it.pTextColor)
  }
}

,此扩展程序的用法在这里 cardView.setTheme(theme)

如何获得这个cardView.theme = theme

1 个答案:

答案 0 :(得分:2)

您可以编写扩展功能:

fun CardView.setTheme(theme: Theme) {
    val titleText = findViewById<TextView>(R.id.text)
    val contentText = findViewById<TextView>(R.id.content)
    titleText.setTextColor(theme.pTextColor)
    contentText.setTextColor(theme.pTextColor)
}

或扩展属性:

var CardView.theme: Theme?
    get() = null
    set(value) {
        value ?: return
        val titleText = findViewById<TextView>(R.id.text)
        val contentText = findViewById<TextView>(R.id.content)
        titleText.setTextColor(value.pTextColor)
        contentText.setTextColor(value.pTextColor)
    }