android - 从协程更改布局
问题描述
协程启动
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.
解决方案
因为GlobalScope.launch()
在不指定协程上下文的情况下使用将在后台线程上运行您的代码Dispatchers.Default
,而不是 MainThread,您只能通过 MainThread 协程的上下文与 UI 通信
GlobalScope.launch(){
get_message_pulling()
withContext(Dispatchers.Main) {
// then update the UI
}
}
推荐阅读
- mongodb - kuberetes hostPort 声明不适用于 StatefulSet 中的 pod,需要任何额外的配置吗?
- logstash - 使用预定义的 grok 过滤器将单词连接到电子邮件
- botframework - 如何训练 LUIS 识别一般名词?
- release-management - 在发布管理中加快下载工件
- windows - 浏览器在 Windows 10 中无法访问虚拟机开发网站
- java - 如果为真,则创建虚拟字符串并返回错误消息
- python - 类型错误:在 django 2.0 中的 include() 情况下,View 必须是可调用的或列表/元组
- javascript - 使用范围滑块更改 div 的高度
- angular - 实现秒表的最有效方法?
- python - 使用循环在 plotly 中定义多个 y 轴