2

I want to create a function that runs every 50ms (the equivalent of setInterval in JS). So far, this is what I have:

val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post(object: Runnable {
    override fun run() {
        progressBar.progress += 1
        mainHandler.postDelayed(this, 50)
    }
})

It works, but how do I stop the run() function from running any further when the progress has reached 100? Also, is there a way to cancel the run and reset progress to 0 when I click a button (like clearInterval in JS)? For reference, I want this:

buttonView.setOnClickListener {
    stopRunFromRunning()
    resetProgressTo0()
}

progress.onReach100 {
    stopRunFromRunning()
}
1

2 Answers 2

3

assign the runnable into a variable and you can remove from handler's callback

val progressBar = findViewById(R.id.progress_bar)
val btn = findViewById(R.id.btn)

val handler = Handler(Looper.getMainLooper())
val runnable = Runnable {
    override public fun run() {
     progressBar.progress+=1
       if(progressBar.progress<100)
          handler.postDelayed(this, 50) 
    }
}

handler.post(runnable, milliseconds)

btn.setOnClickListener {
    handler.removeCallbacks(runnable)
    progressBar.progress=0
}

4
  • this doesn't answer any of his questions
    – Tim
    Dec 12, 2019 at 14:55
  • Actually, it does. Dec 12, 2019 at 15:25
  • @EpicPandaForce it's not a complete answer. Believe me, I just won my new hat :) Dec 12, 2019 at 15:30
  • Thanks, this answers my question. However, if you have time, please do add some implementation on the other conditions I mentioned (on button click and on progress reaching 100, e.g. by adding return inside the run() after progress reaches 100 and removing itself from its run()). I will accept your answer after that.
    – Richard
    Dec 12, 2019 at 16:30
0

when working with progressbar, I do something like:

var stop = false
val runnable = Runnable {
       while (progressBar.progress < 100) {
            if(stop) break

            progressBar.progress += 1
            // Try to sleep the thread for 50 milliseconds
            try {
                Thread.sleep(50)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
       }
}
Thread(runnable).start()

// stop
stopButtonClick -> {
    stop = true
    progressBar.progress = 0
}

now you can tell your counter to stop before progressBar.progress = 100 and your counter also knows when to stop itself. Hope it helps

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.