首页 > 解决方案 > 为什么在这段代码中使用 this@MainActivity?

问题描述

我在MainActivity类中看到了这样的代码:

class MainActivity : AppCompatActivity() {
    private val languages = arrayOf("One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten")
    private var index = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textSwitcher.setFactory {

            val textView = TextView(this@MainActivity) //the line I was 
                                                       //talking about.

            textView.gravity =  Gravity.CENTER_HORIZONTAL
            textView.textSize = 32f
            textView.setTextColor(Color.BLACK)
        }
        textSwitcher.setText(languages[index])
    }
}

但我没明白。“ this ”关键字已经不代表MainActivity了?如果是这样,为什么需要标签?

我编写了该代码来理解“this”关键字。

class class1(c:class2){
    init{
        c.output()
    }
}
class class2{
    init{
        class1(this) // this" keyword represent the class2
    }
    fun output(){
        println("Hello.")
    }
}
fun main(){
    val x = class2()
}

标签: androidkotlinlabelthis

解决方案


与您有关的行在 lambda 表达式中,Kotlin 正在将其转换为amakeView()函数实现ViewSwitcher.ViewFactory。因此,在该 lambda 表达式的范围内,thisViewSwitcher.ViewFactory,而不是MainActivity. 所以,我们需要@MainActivity标签来表明我们想要外部MainActivity对象的表示this

https://developer.android.com/reference/kotlin/android/widget/ViewSwitcher?hl=en#setfactory


推荐阅读