0

let's say I'm making a simple dnd dice roller (cause I am), I made it so it rolls a bunch of random numbers based on how many dice they want rolled and the type of dice. it then sends it to a text view one at a time(what I want); However, it only shows one number because it has no delay to let the the user see each number rolled (it only shows the last number).

How would I do that?

    else if (numTimesRolled.progress <= 4) {
            for (i in 0 until numTimesRolled.progress){
                randNum = Random.nextInt(1, diceIsComfirm)
                resultsArray[i] = randNum.toString()
            }
            for (i in 0 until numTimesRolled.progress){
                randNumDisplay.text = resultsArray[i]
            }
Ray Paxman
  • 23
  • 4
  • 1
    A handler would be an easy solution see, https://stackoverflow.com/questions/5623578/android-delay-using-handler. Since you're using kotlin, you could also use coroutines, but that's a little bit more involved if you don't have experience with them. – Nicolas Sep 14 '21 at 21:47
  • I'm going to look into both. I tried looking into handlers a little. I appreciate your insight. – Ray Paxman Sep 15 '21 at 02:46
  • So I got a handler somewhat working, but it's not working how I intended. It is giving slight delay to whatever comes into the textview somewhat, but only the last numbers out of many dice rolled. I'm pretty sure I'm just placing the handler in the wrong spot, but I do not know the right one. Do you have any advice for handlers? also It fine if you don't wanna reply, just looking for a quick solution. – Ray Paxman Sep 15 '21 at 23:16

1 Answers1

1

Non-coroutines solution is to post Runnables:

val delayPerNumber = 500L // 500ms
for (i in 0 until numTimesRolled.progress){
    randNumDisplay.postDelayed({ randNumDisplay.text = resultsArray[i] }, i * delayPerNumber)
}

With a coroutine:

lifecycleScope.launch {
    for (i in 0 until numTimesRolled.progress){
        delay(500) // 500ms
        randNumDisplay.text = resultsArray[i]
    }
}

An advantage with the coroutine is it will automatically stop if the Activity or Fragment is destroyed, so if the Activity/Fragment is closed while the coroutine's still running, it won't hold your obsolete views in memory.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • thank you for your answer, I will take reference from it. I have just started out so I don't know much about co routines and how they work exactly. – Ray Paxman Sep 15 '21 at 02:49