我是科特林的初学者。我尝试创建一个每2秒重复一次的任务。所以我创建了这样的内容。
val handler = Handler()
handler.postDelayed(Runnable {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}, 2000)
但是在postDelayed(this)中,它给出错误-required Runnable!, found MainActivity
。我什至尝试过this@Runnable
,但没有成功。
但是当我像这样编写相同的函数时,它会起作用
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}
}, 2000)
所以this
关键字为什么在第一个函数中不起作用,但是在第二个函数中却很好?
第一个是接受lambda并返回Runnable
的函数。在这种情况下,this
毫无意义。
[第二个您正在定义实现Runnable
的匿名对象。在这种情况下,this
引用该对象实例。