对不起,我是Kotlin的新手,所以请多多包涵。
我有这个代码
Class A :Basefragment()
{
...
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.save) {
val thread = SimpleThread(editTitle.text.toString(), editDescription.text.toString())
thread.start()
}
}
inner class SimpleThread(title: String, description: String) : Thread() {
override fun run() {
var titles = title // how to use title ?
}
}
}
在SimpleThread中,如何获取标题值?我得到未解决的引用
答案 0 :(得分:2)
您当前的语法仅将title
和description
作为构造函数参数传递,您可以使用它们来初始化属性或在init
块中:
inner class SimpleThread(title: String, description: String) : Thread() {
val title = title
init {
println(description)
}
}
虽然您可以将这些值保存到如上所述的属性中,但也可以将val
或var
直接添加到构造函数中,以创建采用构造函数参数值的属性:
inner class SimpleThread(val title: String, val description: String) : Thread() { ... }
现在可以随时通过任何功能访问这些保存的属性,而不仅仅是在构造时。