
Timer + TimerTask 每 100ms 觸發一次。Handler 切回主執行緒更新 UI。RotateAnimation 控制指針旋轉,TextView 顯示剩餘秒數。public class CountdownActivity extends Activity {
private long totalTicks = 50; // 50 * 100ms = 5秒
private long currentTick = 0;
private TextView tvTime;
private ImageView dial, hand;
private Timer timer;
private TimerTask task;
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
if (totalTicks <= 1) { stop(); return; }
totalTicks--; currentTick++;
int seconds = (int) (totalTicks / 10);
// 旋轉動畫:每 tick 36 度 (360/10)
float fromDeg = (currentTick - 1) * 36f;
float toDeg = currentTick * 36f;
RotateAnimation anim = new RotateAnimation(fromDeg, toDeg,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(100);
anim.setFillAfter(true);
hand.startAnimation(anim);
dial.startAnimation(anim);
tvTime.setText(String.format("%02d", seconds));
}
};
private void start() {
if (timer != null) return;
task = new TimerTask() {
@Override public void run() {
handler.sendEmptyMessage(1);
}
};
timer = new Timer(true);
timer.schedule(task, 100, 100); // 100ms 延遲,100ms 間隔
}
private void stop() {
if (task != null) { task.cancel(); task = null; }
if (timer != null) { timer.cancel(); timer.purge(); timer = null; }
handler.removeMessages(1);
}
@Override protected void onDestroy() { stop(); super.onDestroy(); }
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@android:color/background_dark">
<ImageView android:id="@+id/duocimin_dial"
android:layout_centerInParent="true"
android:src="@drawable/iv_bg"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<ImageView android:id="@+id/duocimin_progress"
android:layout_centerInParent="true"
android:src="@drawable/min_progress"
android:visibility="invisible"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<ImageView android:id="@+id/duocimin_progress_hand"
android:layout_centerInParent="true"
android:src="@drawable/min_progress_hand"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView android:id="@+id/duocitvTime"
android:layout_centerInParent="true"
android:textSize="35sp" android:textStyle="bold"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="@+id/startbuttonduoci"
android:text="開始" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/>
</RelativeLayout>
iv_bg:表盤背景。min_progress:進度弧(可透明)。min_progress_hand:指針圖片(錨點置中)。結合 Timer 精準計時與 RotateAnimation 平滑旋轉,即可實現電影倒計時視覺效果,適用於遊戲倒數、拍照延遲等場景。