localChatManager.addIncomingListener { from, message, chat ->

                Log.v(TAG,"listener")


                //You can't modify views from non-UI thread.
                this@chatActivity.runOnUiThread { object :Runnable{
                    override fun run() {
                        Log.i(TAG,"runOnUiThread")
                     }
                } }
            }

我不明白为什么runOnUiThread不起作用,但在这种方法之外,一切都正常.

推荐答案

您要做的是将lambda传递给runOnUiThread函数.它将运行该lambda,并创建一个继承自Runnableobject,然后对其不做任何处理.如果您将其格式化为这样(添加了一些额外的日志(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.

Kotlin相关问答推荐

用普通Kotlin理解Gradle的Kotlin DSL'""

在KMM合成多平台中创建特定于平台的视图

如何访问方法引用的接收者?

Android Studio中的只读集合不支持操作失败的原因是什么?

try 一次性插入多条记录时,JOOQ连接为空错误

垂直滚动条下拉菜单的桌面组合

列表在 android WebView 中没有正确迭代

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

Kotlin 接口类型参数

Flow.state In() 未从其来源接收新值

高效匹配两个 Flux

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

类型是什么意

如何使用 Kotlin Coroutines 使 setOnClickListener debounce 1 秒?

在 Koin 中提供一个 Instance 作为其接口

将 @Component.Builder 与构造函数参数一起使用

如何处理 Kotlin 中的异常?

requireNotNull vs sure !! 操作符

Kotlin-通过与属性列表进行比较来筛选对象列表