Android 在内部类Kotlin中获取外部值
对不起,伙计们,我是科特林的新手,所以请容忍我 我有这个密码Android 在内部类Kotlin中获取外部值,android,kotlin,Android,Kotlin,对不起,伙计们,我是科特林的新手,所以请容忍我 我有这个密码 Class A :Basefragment() { ... override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == R.id.save) { val thread = SimpleT
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中,如何获取标题值?我得到未解析的引用您当前的语法仅作为构造函数参数传入
标题
和描述
,您可以使用构造函数参数初始化属性,或在初始化
块中:
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() { ... }
现在,您可以随时从任何函数访问这些保存的属性,而不仅仅是在构造时。您当前的语法仅作为构造函数参数传入
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() { ... }
现在,可以随时从任何函数访问这些保存的属性,而不仅仅是在构造时。
title
是构造函数参数,而不是var
/val
参数。您可能会得到一个错误,它是未使用的;这与内部类无关。title
是构造函数参数,但不是var
/val
参数。您可能会得到一个错误,它是未使用的;这与内部类无关。