【问题标题】:Only the original thread that created a view hierarchy can touch its views [2]只有创建视图层次结构的原始线程才能接触其视图 [2]
【发布时间】:2022-03-03 07:08:14
【问题描述】:

当我尝试启动应用程序时,一秒钟后应用程序崩溃并出现在 LOGCAT 中:

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

我所期待的:当应用程序打开时,它会显示设备的小时、分钟和秒,并每秒永久更新

代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Timer().schedule(object : TimerTask() {
            override fun run() {
                val textView: TextView = findViewById(R.id.dateAndTime)
                val simpleDateFormat = SimpleDateFormat("HH:mm:ss z")
                val currentDateAndTime: String = simpleDateFormat.format(Date())
                textView.text = currentDateAndTime
            }
        }, 1000)
    }

} 

【问题讨论】:

  • 我认为您的链接是关于 Java,而不是 Kotlin。 @lukas.j
  • 与 Timer 关联的线程是后台。并且从后台线程你试图访问主线程 UI 元素因此这给出了这个错误
  • @Luiz:这是关于 Android 的。除了 UI 线程,您不能从任何线程修改视图。

标签: android kotlin


【解决方案1】:

计时器线程在与视图不同的线程上运行

把你的代码改成这个

val textView: TextView = findViewById(R.id.dateAndTime)

Timer().schedule(object : TimerTask() {
            override fun run() {
              
                val simpleDateFormat = SimpleDateFormat("HH:mm:ss z")
                val currentDateAndTime: String = simpleDateFormat.format(Date())

//This does the trick
runOnUiThread{
                textView.text = currentDateAndTime
}
            }
        }, 1000)

【讨论】:

  • 由于某种原因,文本没有被编辑,但现在没有错误。
  • 您可以尝试记录 currentDateAndTime 看看它是否在变化
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多