只有创建视图层次结构的原始线程才能接触其视图[2]



当我尝试启动应用程序时,一秒钟后应用程序崩溃,这会出现在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)
}
} 

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

将您的代码更改为此

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)

最新更新