N
N
Newbie Ivanovich2020-04-03 14:08:02
Android
Newbie Ivanovich, 2020-04-03 14:08:02

How to pass this to handler.postDelayed kotlin?

The error occurs in the this parameter passed to the handler.postDelayed method

class MainActivity : AppCompatActivity() {
    private var s:Int = 0
    private var running: Boolean = false
    fun onClickStart(view: View) {
        running = true
    }
    fun onClickStop(view: View) {
        running = false
    }
    fun onClickReset(view: View) {
        running = false
        s = 0
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        runTimer()
    }

    private fun runTimer() {
        val time_view = findViewById<TextView>(R.id.time_view)
        val handler: Handler = Handler()
        handler.post(
            Runnable {
                @Override
                fun run() {
                    var hours:Int = s/3600
                    var minutes: Int = (s%3600)/60
                    var secs:Int = s%60
                    var time:String = String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, secs)
                    time_view.setText(time)
                    if(running) {
                        s++
                    }
                    handler.postDelayed(this,1000)
                }
            }
        )

    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-04-03
@NovichokIvanovich

you have an error in the definition of Runnable

Runnable {
                @Override
                fun run() {

This is not how it is written in Kotlin. Here you declared a lambda, and inside it - the run function. Override is simply ignored. this will be the enclosing class.
It will be right
object: Runnable {
    override fun run() {
        handler.postDelayed(this)
    }
}

What you wanted to do is a lambda that implements a Java SAM interface. You can do this if you don't need this inside. It will look like this:
Runnable {
   //тут код, который должен быть в run()
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question