我想在Android中做Kotlin,但我有一些关于mutable的问题。我们假设我正在通过多种方法访问model {
Person person
}
json {
id person.id
displayName person.displayName
dateOfBirth g.formatDate(date: person?.dateOfBirth, format: 'dd-MM-yyyy')
}
。
TextView
这很有效,但每次使用TextView时var tv: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
tv = find(R.id.tv)
}
fun clearText(){
tv?.setText("")
}
fun setText(text: String) {
tv?.setText(text)
}
都有代码味道。有没有更好的方法呢?我觉得我应该使用tv?
代替val
,但我无法找到将其放入的方法。
答案 0 :(得分:6)
我知道解决这个问题的两种方法。 Lateinit和Kotlin's Android extensions。
Lateinit允许您在类生命周期的后期为非null类型赋值。
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?){
textView = findViewById(R.id.view_text)
}
您现在可以在不进行空检查的情况下访问它。
或者,您可以使用Kotlin的扩展程序。
将插件添加到build.gradle
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
将生成的访问器导入Activity,Fragment或其他任何内容。
import kotlinx.android.synthetic.main.layout_name.*
text_view_id.text = "Hello World!"