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

Android 閃爍背景效果:Handler 實現精確定時交替顏色

     編輯:程式設計綜合問答

錯誤嘗試

// 主線程睡眠會導致 ANR,UI 不更新
Thread.sleep(100);
layout.setBackgroundColor(Color.BLACK);
Thread.sleep(20);

正確方案:Handler.postDelayed

public class StrobeActivity extends Activity {
    private LinearLayout layout;
    private Handler handler = new Handler();
    private boolean toggle = true;
    private final Runnable strobeRunnable = new Runnable() {
        @Override public void run() {
            layout.setBackgroundColor(toggle ? Color.WHITE : Color.BLACK);
            toggle = !toggle;
            long delay = toggle ? 100 : 20; // 白100ms,黑20ms
            handler.postDelayed(this, delay);
        }
    };

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_strobe);
        layout = findViewById(R.id.strobe_layout);
        handler.post(strobeRunnable); // 啟動
    }

    @Override protected void onDestroy() {
        handler.removeCallbacks(strobeRunnable); // 停止防洩漏
        super.onDestroy();
    }
}

關鍵點

  • 所有 UI 操作在主線程,Handler 綁定主線程 Looper。
  • postDelayed 實現非阻塞定時循環。
  • onDestroy 移除回調防止內存洩漏和崩潰。
  • 全屏主題 android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 效果更佳。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved