Home > front end >  How can I set a CountDownTimer in Kotlin?
How can I set a CountDownTimer in Kotlin?

Time:10-10

Using the CountDownTimer, is there a way I can let the user choose how much time the timer will count?

val timer = object : CountDownTimer(time * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            bntTimer.text = (millisUntilFinished / 1000).toString()
            if (!on)
                turnOn()
        }

        override fun onFinish() {
            bntTimer.text = "Timer"
            if (on)
                turnOff()
        }
    }

In this code the variable time is initialized with 5, but before starting the timer, the user can change it. However, it always count 5 seconds.

Here is where the variable time got modified

 bntTimer.setOnClickListener(){
        if(TextUtils.isEmpty(etTime.text)) {
            Toast.makeText(this, "Por favor, informe o tempo.", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(this@MainActivity, "Timer Contando", Toast.LENGTH_SHORT).show()
            time = etTime.text.toString().toLong()
            timer.start()
        }
    }

CodePudding user response:

The problem is you are making the timer object first then changing the time variable which has no longer effect on the existing timer object. So you must make the timer object again after changing the time variable.

You can make a function like below or a function with time as a parameter.

fun starTimer(){

    time = etTime.text.toString().toLong()

    val timer = object : CountDownTimer(time * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            bntTimer.text = (millisUntilFinished / 1000).toString()
            if (!on)
                turnOn()
        }

        override fun onFinish() {
            bntTimer.text = "Timer"
            if (on)
                turnOff()
        }
    }.start()
}

Then call the startTimer() function whenever you need it. Something like in your case

 bntTimer.setOnClickListener(){
        if(TextUtils.isEmpty(etTime.text)) {
            Toast.makeText(this, "Por favor, informe o tempo.", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(this@MainActivity, "Timer Contando", Toast.LENGTH_SHORT).show()
            startTimer()
        }
    }
  • Related