首页 > 解决方案 > 从协程更改布局

问题描述

协程启动

GlobalScope.launch(){
    get_message_pulling()
}

我需要从中编辑布局get_message_pulling(),但出现错误

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

标签: androidkotlinkotlin-coroutinescoroutine

解决方案


因为GlobalScope.launch()在不指定协程上下文的情况下使用将在后台线程上运行您的代码Dispatchers.Default,而不是 MainThread,您只能通过 MainThread 协程的上下文与 UI 通信

GlobalScope.launch(){
   get_message_pulling()

    withContext(Dispatchers.Main) {
       // then update the UI 
    }
}

推荐阅读