android - 为什么在这段代码中使用 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()
}
解决方案
与您有关的行在 lambda 表达式中,Kotlin 正在将其转换为a的makeView()
函数实现ViewSwitcher.ViewFactory
。因此,在该 lambda 表达式的范围内,this
是ViewSwitcher.ViewFactory
,而不是MainActivity
. 所以,我们需要@MainActivity
标签来表明我们想要外部MainActivity
对象的表示this
。
https://developer.android.com/reference/kotlin/android/widget/ViewSwitcher?hl=en#setfactory
推荐阅读
- django - 更改数据库后重新启动 Django 服务器
- c# - 如何实现 Android ISO 并将其加载到 C# WinForm 应用程序中?
- marklogic - 路径范围索引方面搜索在 Marklogic 9 中不起作用
- java - Mockito 让 mock 从现有的 mock 继承存根
- reactjs - 如果父组件卸载,防止子道具更新
- highcharts - 停止 HighCharts 在悬停一个系列时更改另一个系列的透明度
- python - 尝试从 github Enterprise 克隆时连接被拒绝
- symfony - 按字段对学说的@OneToMany ArrayCollection 进行排序
- javascript - 如何将 rabbitMQ 连接分配给类的属性以在另一个函数中使用它?
- javascript - 从 JSON 数组中检索与键相关的特定值