Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

android - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...