下面是我的简单代码和logcat
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)
println("onCreate " + Thread.currentThread().name)
Thread(){
println("Thread " + Thread.currentThread().name)
textView.text = "1"
}.start()
textView.setOnClickListener {
Thread(){
println("Thread click " + Thread.currentThread().name)
textView.text = "1"
}.start()
}
}onCreate main
Thread Thread-2我不明白为什么我可以在Thread-2上更新ui
然后单击textView并获取日志
onCreate main
Thread Thread-2
Thread click Thread-3应用程序崩溃并获取错误Only the original thread that created a view hierarchy can touch its views.
这没问题,因为我不能在Thread-3上更新ui。
但是为什么Thread-2可以呢?
发布于 2021-08-31 08:57:12
只在主线程上更新UI并不是所有地方都严格执行的,有时视图系统处于一种您可以逃脱惩罚的状态。你无论如何都不应该这样做。
您可以检查Only the original thread that created a view hierarchy can touch its views的堆栈跟踪,以了解主线程强制在您的案例中的位置。
发布于 2021-08-31 08:45:45
UI只能在主线程中更新
runOnUiThread {
//code that runs in main
}https://stackoverflow.com/questions/68995384
复制相似问题