R
R
RobCapa2021-04-25 19:42:40
Android
RobCapa, 2021-04-25 19:42:40

How to update the user interface while running?

In the process of learning kotlin and android studio, I decided to do a seemingly banal thing: a timer. All you have is a button, here is a textView, clicked on the button, the for loop started and know for yourself substitutes a new value in the textView, falls asleep for a second and then again. But I learned a little nuance: all UI elements refuse to update until onResume completes (at least that's what it looks like). And so this code:

override fun onResume() {
    super.onResume()
    
    for(i in 1..10) {
        bindingClass.textView.text = i.toString()
        Thread.sleep(1000)
    }
}

It only leads to the fact that the application seems to hang for 10 seconds, and then immediately shows "10" on the screen. I tried to launch in a separate coroutine via runBlocking { launch {} } , but the result is the same.

What is the best way to achieve the desired result? And is it really such a rare task to update the user interface while the application is running that Kotlin did not add some prepared way to do this? At least I couldn't find it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
surodeev_artem, 2021-04-28
@RobCapa

Alternatively, you can use a Handler:
At the class level:
lateinit var timer: Runnable
In a function:

val handler = Handler()
var iterator = 1
timer = Runnable() {
        textview.text = iterator.toString()
        if (iterator++ < 10) {
                handler.postDelayed(timer, 1000)
        }
}
handler.post(timer)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question