簡體   English   中英

如何在 Kotlin 中暫停計時器 Object

[英]How to pause a timer Object in Kotlin

我在活動中使用這段代碼來顯示計時器倒計時:

//SET COUNTDOWN TIMER in onCreate()
     //var tempo is a :Long number

        var textView = findViewById<TextView>(R.id.countdownTimer)
        object : CountDownTimer(tempo, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                textView.setText("Remaining time: "+tim(millisUntilFinished) )
            }

            override fun onFinish() {
                textView.text = "Times up!"
            }

        }.start() 

如果可能的話,我想實現在onBackPressed()中暫停此 CountDownTimer 並再次恢復它的可能性?

override fun onBackPressed() {
        AlertDialog.Builder(this).apply {
            setTitle("Confirm")
            setMessage("Exit app?")

            setPositiveButton("Yes") { _, _ ->
                // if user press yes, cancel timer?
                super.onBackPressed()
            }

            setNegativeButton("No"){_, _ ->
                // if user press no, then return the activity and resume timer?
            }

            setCancelable(true)
        }.create().show()
    }

我的想法是在每次 OnBackPressed 時編輯var tempo區分它,並在 onCreate() 中復制第一個代碼段的部分並將其放在 onResume() 中。

我對使用這個 tbh 感到很困惑。 也許有更快更好的方法?

您不能暫停CountDownTimer 您可以做的是停止它,然后在您想要恢復它時啟動另一個(剩余時間)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM