在Android中,實現倒計時可以使用Handler和Runnable來實現。以下是一個簡單的示例代碼:
public class CountDownTimerActivity extends AppCompatActivity {
private TextView mTextViewCountdown;
private int mCountdown = 10;
private Handler mHandler;
private Runnable mRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down_timer);
mTextViewCountdown = findViewById(R.id.textview_countdown);
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
if (mCountdown > 0) {
mTextViewCountdown.setText(String.valueOf(mCountdown));
mCountdown--;
mHandler.postDelayed(this, 1000); // 每隔1秒執行一次
} else {
mTextViewCountdown.setText("倒計時結束");
}
}
};
mHandler.post(mRunnable);
}
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(mRunnable);
}
}
在上面的示例中,首先在布局文件中定義了一個TextView用于顯示倒計時,然后在Activity中創建了Handler和Runnable對象。在Runnable中實現了每隔1秒更新一次倒計時并更新TextView的邏輯。在Activity的onCreate()方法中調用Handler的post()方法來啟動倒計時,同時在onPause()方法中移除Runnable以停止倒計時。