Kotlin - 闪烁文本的最简单方法(可见/不可见)

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

我正在尝试使文本闪烁(基于之前的按钮点击),但我的应用程序在 1000 毫秒/2000 毫秒后崩溃。

我试过创建一个线程,但我不确定这是否是最简单的方法。有人可以帮助我吗?

这是我当前的代码:

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()*/

提前致谢

使用Handler and make use of its postDelayed方法。当你想改变 UI 时,你需要使用主循环程序:val uiCallbackHandler: Handler = Handler(Looper.getMainLooper())。除此之外你还需要两件事:

  1. 创建 Runnable 来定义您的 UI 交替逻辑
  2. Post 延迟了您当前用于线程休眠的 1000 毫秒。

结合使用我的建议和您的代码(我也让它更像 Kotlin):

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