【发布时间】: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 线程,您不能从任何线程修改视图。