當我嘗試啟動應用程式時,一秒鐘后應用程式崩潰并出現在 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)
}
}
uj5u.com熱心網友回復:
計時器執行緒在與視圖不同的執行緒上運行
將您的代碼更改為此
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/434237.html
上一篇:對Reactnative的承諾
