界面包含一個按鈕和一個 TextView(作為燈泡),點擊按鈕後 TextView 每隔 2 秒閃爍一次。
核心思路:利用 Handler 或 Timer 定時切換 TextView 的背景色或圖片資源。
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 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();
ObjectAnimator 操作 alpha 屬性。