android - 我被困在 Kotlin While-Loop 中了吗?
问题描述
我在做倒数计时器。
当我按下暂停按钮或停止按钮时效果很好,但当我按下开始按钮时应用程序冻结。
我怀疑我陷入了 while 循环,但算法在 while 循环之前没有到达代码。
我的代码有什么问题?
class MainActivity( var second : Int = 0 , var minute : Int = 0 , var hour : Int = 0 , var ongoing : Boolean = false ) : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initLayout()
}
private fun initLayout(): Unit {
val startButton: Button = findViewById(R.id.startButton)
val pauseButton: Button = findViewById(R.id.pauseButton)
val stopButton: Button = findViewById(R.id.stopButton)
var realTime : TextView = findViewById(R.id.Realtime)
startButton.setOnClickListener {
realTime.text = "0"//doesn't reach here
buttonOn()
countTime(realTime)
}
pauseButton.setOnClickListener {
buttonOff()
countTime(realTime)
}
stopButton.setOnClickListener {
buttonOff()
countTime(realTime)
}
}
private fun buttonOn(): Unit {
this.ongoing = true
}
private fun buttonOff(): Unit {
this.ongoing = false
}
private fun showTime(second: Int, minute: Int, hour: Int): String {
var secondShow: String = if (second < 10) "0$second" else second.toString()
var minuteShow: String = if (minute < 10) "0$minute" else minute.toString()
var hourShow: String = if (hour < 10) "0$hour" else hour.toString()
return "$hourShow:$minuteShow:$secondShow"
}
private fun countTime(textView: TextView): Unit {
var text = 0
textView.text = text.toString()
textView.text = showTime(this.second, this.minute, this.hour)
while (this.ongoing) {
Thread.sleep(1_000)
this.second++
if (this.second == 60) {
this.second = 0
this.minute++
if (this.minute == 60) {
this.minute = 0
this.hour++
}
}
textView.text = showTime(this.second, this.minute, this.hour)
//buttonOff reach here
}
}
}
解决方案
推荐阅读
- c - C linux:串行通信在接收数据时丢失了一些第一个字节
- azure-functions - Azure Function .NET5 隔离进程从 HttpRequestData 获取路径参数
- git - 如何在 TFS 上移植 git 更改?
- python - 为什么请求响应中的 html 会偏离开发工具?
- javascript - Extjs:如何在拖动时禁用文本选择并保持自动滚动?
- c - 循环索引的伪代码以 2 开头
- c++ - 就地创建 std::optional
- pyspark - pyspark.sql.utils.AnalysisException:参考“cte5.cte5_cnt”不明确
- javascript - 如何将数组奇数位置的值加倍,并返回完整数组?
- javascript - MediaElement 跟踪观看时间