Home > Net >  Android kotlin update TextView every second
Android kotlin update TextView every second

Time:08-02

I want the text view to be updated every second or less in a dynamic random way and at the end of the loop the text view show the last random number. I tried to add a sleep method but it did not work every time I click the button the text view show the last random number directly.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rollButton: Button = findViewById(R.id.button1)
        var result: TextView = findViewById(R.id.textView)

        rollButton.setOnClickListener {
            for (i in 1..10){
                result.text = "${(1..6).random()}"
            }
            Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT).show()
        }
    }
}

CodePudding user response:

You can use Coroutine delay

  rollButton.setOnClickListener {
        CoroutineScope(Dispatchers.Main).launch {
                   //Disable button temporarily to prevent multiple clicks
                    it.isEnabled = false
                    for (i in 1..10) {
                        binding.textviewFirst.text = "${(1..6).random()}"
                        //One second delay before the next
                        delay(1000)

                       //If you want random delay - say 100ms to 1s
                       //delay((100L..1000L).random())
                    }
                    it.isEnabled = true
                    Toast.makeText(this@MainActivity, "Dice Rolled!", Toast.LENGTH_SHORT).show()
                }
            }

CodePudding user response:

Coroutine delay is a way to do that, which is suggested in ltp's answer, Another way is Runnable and Handler, an example function:

    fun animateTextView(handler: Handler, textView: TextView, animate: Boolean = true) {
        val runnable: Runnable = object : Runnable {
            var randomNumber = 0
            override fun run() {
                randomNumber = {(1..100).random()}
                textView.text = "$randomNumber"
                handler.postDelayed(this, 500L)
            }
        }

        // animate == false -> end text updates
        if (animate) handler.postDelayed(runnable, 500L)
        else handler.removeCallbacks(runnable)
    }

Example use of the function:

    private val textAnimaterHandler = Handler(Looper.getMainLooper())
    animateTextView(textAnimaterHandler, binding.textView)
    // Stop updates:
    animateTextView(textAnimaterHandler, binding.textView, animate = false)

  • Related