androidmultithreadingkotlinblink

Kotlin - Easiest way to blink text (visible / invisible)


I'm trying to blink a text (based on a previous button click) but my App crashes after 1000ms/2000ms.

I have tried to create a thread but I'm not sure if it is the easiest way. Can someone help me?

This is my current code:

fun toggleBlinkCounterUI() {

        /*var handler: Handler = Handler();
        Thread(Runnable() {
            override fun run() {
                var timeToBlink: Long = 1000;
                    Thread.sleep(timeToBlink)

                handler.post(Runnable() {
                    fun run() {
                        if (binding.exerciseTimer.visibility == View.VISIBLE){
                            binding.exerciseTimer.visibility = View.INVISIBLE
                        } else {
                            binding.exerciseTimer.visibility = View.VISIBLE
                        }
                        toggleBlinkCounterUI();
                    }
                });
            }
        }).start();*/

        /*val thread = Thread {
            var timeToBlink: Long = 1000;

            while (1 == 1) {
                Thread.sleep(timeToBlink)
                if (binding.exerciseTimer.visibility == View.VISIBLE){
                    binding.exerciseTimer.visibility = View.INVISIBLE
                } else {
                    binding.exerciseTimer.visibility = View.VISIBLE
                }
            }
        }
        thread.start()*/

Thanks in advance


Solution

  • Use Handler and make use of its postDelayed method. As you want to change the UI you need to use the main looper: val uiCallbackHandler: Handler = Handler(Looper.getMainLooper()). Apart from that you need two more things:

    1. Create Runnable that will define your UI alternation logic
    2. Post delayed with the 1000 millis you currently use for thread sleeping.

    Making use of combination of my suggestions and your code (I also made it a bit more Kotlin-ish):

    val handler = Handler(Looper.getMainLooper())
    val switchVisibilityRunnable = Runnable {
      binding.exerciseTimer.isVisible = !binding.exerciseTimer.isVisible
      handler.postDelayed(switchVisibilityRunnable, 1000)
    }
    handler.post(switchVisibilityRunnable)