首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 使用 TextView 模擬燈泡閃爍效果的實現思路

     編輯:程式設計綜合問答

需求描述

界面包含一個按鈕和一個 TextView(作為燈泡),點擊按鈕後 TextView 每隔 2 秒閃爍一次。

實現方案

核心思路:利用 Handler 或 Timer 定時切換 TextView 的背景色或圖片資源。

方案一:Handler + Runnable(推薦)

private Handler handler = new Handler();
private Runnable blinkRunnable = new Runnable() {
    @Override
    public void run() {
        textView.setBackgroundColor(currentColor == Color.YELLOW ? Color.BLACK : Color.YELLOW);
        currentColor = (currentColor == Color.YELLOW) ? Color.BLACK : Color.YELLOW;
        handler.postDelayed(this, 2000); // 2秒循環
    }
};

// 按鈕點擊啟動
button.setOnClickListener(v -> handler.post(blinkRunnable));

// 停止閃爍(如需)
// handler.removeCallbacks(blinkRunnable);

方案二:ValueAnimator(屬性動畫)

ValueAnimator animator = ValueAnimator.ofInt(0, 1);
animator.setDuration(2000);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.addUpdateListener(animation -> {
    int value = (int) animation.getAnimatedValue();
    textView.setBackgroundColor(value == 0 ? Color.YELLOW : Color.BLACK);
});
animator.start();

注意事項

  • 在 Activity/Fragment 銷毀時務必移除回調或取消動畫,防止內存洩漏。
  • 若需更豐富效果(如漸變),可使用 ObjectAnimator 操作 alpha 屬性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved