您要做的是将lambda传递给runOnUiThread
函数.它将运行该lambda,并创建一个继承自Runnable
的object
,然后对其不做任何处理.如果您将其格式化为这样(添加了一些额外的日志(log)语句和解释),也许您可以更好地看到这一点:
runOnUiThread({
Log.i(TAG, "This is run")
object : Runnable { // This whole expression
override fun run() { // returns an object which
Log.i(TAG, "runOnUiThread") // is a Runnable, but does
} // not at any point invoke
} // its "run" method
Log.i(TAG, "And so is this")
})
The created object
is not assigned to a variable, and is never used. If you want to pass in a Runnable
instance to the runOnUiThread
method, you can do that by just putting it inside the parentheses of the runOnUiThread
call:
runOnUiThread(
object : Runnable {
override fun run() {
Log.i(TAG, "runOnUiThread")
}
}
)
使用runOnUiThread的最简单方法是使用SAM转换将lambda传递给它,并直接在其中编写要执行的代码.
runOnUiThread {
Log.i(TAG, "runOnUiThread")
}
下面是official documentation covering SAM conversions,它在示例中恰好使用了Runnable
.