首页 > 解决方案 > 我被困在 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
        }

    }
}

标签: androidkotlinwhile-looptimer

解决方案


推荐阅读