gpt4 book ai didi

android - 如何编写在 Kotlin Android 中的间隔内循环的计数器

转载 作者:行者123 更新时间:2023-12-04 23:49:22 24 4
gpt4 key购买 nike

我正在尝试使用 Kotlin 在 Android 应用程序中构建倒计时 View 。我目前拥有的代码在运行时使应用程序崩溃。

PS:Integer timer 也应该稍后在应用程序上更改。

var timer:  Int = 50  // Declared globally
private fun timer(){
timer_text.text = timer.toString() // Text view in UI

while (timer > 1){
Handler().postDelayed({
timer--
timer_text.text = timer.toString() // Update the Text view in UI
}, 1000)
}
}

日志

I/sandaru.projec: Thread[6,tid=11100,WaitingInMainSignalCatcherLoop,Thread*=0xb400007b3dcd9f50,peer=0x13280238,"Signal Catcher"]: reacting to signal 3
I/sandaru.projec:
I/sandaru.projec: Wrote stack traces to tombstoned
D/EGL_emulation: app_time_stats: avg=5.51ms min=1.98ms max=10.47ms count=60

最佳答案

看起来有一个 ANR,因为你正在主线程上执行 while 循环,你可以尝试使用下面的代码,这样做会挂起而不是阻塞

var timer:  Int = 50  // Declared globally
private suspend fun timer(){
withContext(Dispatchers.Main) {
timer_text.text = timer.toString() // Text view in UI

while (timer > 1){
timer--
timer_text.text = timer.toString() // Update the Text view in UI
delay(1000)
}
}
}

并且您需要从协程内部执行代码,例如。在 Activity/fragment 中你可以这样执行

lifecycleScope.launch {
timer()
}

关于android - 如何编写在 Kotlin Android 中的间隔内循环的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71539496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com