如何恢复CountDownTimer?

问题描述 投票:0回答:1

我可以通过使用cancel()(timer.cancel())函数成功停止计时器。但是如何恢复呢?我搜索了很多代码,但所有内容都是Java。我在科特林需要它。你能给我建议吗?我使用代码:

val timer = object : CountDownTimer(60000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            textView3.text = (millisUntilFinished / 1000).toString() + ""
            println("Timer  : " + millisUntilFinished / 1000)
        }

        override fun onFinish() {}
    }

编辑:

在班级:

var currentMillis: Long = 0 // <-- keep millisUntilFinished

    // First creation of your timer
    var timer = object : CountDownTimer(60000, 1000) {
        override fun onTick(millisUntilFinished: Long) {

            currentMillis = millisUntilFinished // <-- save value

            textView3.text = (millisUntilFinished / 1000).toString() + ""
            println("Timer  : " + millisUntilFinished / 1000)
        }

        override fun onFinish() {}
    }

在onCreate()中:

  timer.start()

            TextView2.setOnClickListener {
                //Handle click
                timer.cancel()

            }

            TextView3.setOnClickListener {
                //Handle click
                var timer = object : CountDownTimer(currentMillis, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        currentMillis = millisUntilFinished
                        textView3.text = (millisUntilFinished / 1000).toString() + ""
                        println("Timer  : " + millisUntilFinished / 1000)
                    }

                    override fun onFinish() {}
                }
            timer.start()
}
android kotlin countdowntimer
1个回答
0
投票

我的建议:保留millisUntilFinished值并将其用于重新创建CountDownTimer


var currentMillis: Long // <-- keep millisUntilFinished

// First creation of your timer
var timer = object : CountDownTimer(60000, 1000) {
   override fun onTick(millisUntilFinished: Long) {

     currentMillis = millisUntilFinished // <-- save value

     textView3.text = (millisUntilFinished / 1000).toString() + ""
     println("Timer  : " + millisUntilFinished / 1000)
   }

   override fun onFinish() {}
   }
}

...

// You start it
timer.start()

...

// For some reasons in your app you pause (really cancel) it
timer.cancel()

...

// And for reasuming
var timer = object : CountDownTimer(currentMillis, 1000) {
   override fun onTick(millisUntilFinished: Long) {
     currentMillis = millisUntilFinished
     textView3.text = (millisUntilFinished / 1000).toString() + ""
     println("Timer  : " + millisUntilFinished / 1000)
   }

   override fun onFinish() {}
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.