How to implement countdown on Android?
In Android, a countdown timer can be implemented using Handler and Runnable. Here is a simple example code:
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);
}
}
In the example above, a TextView was first defined in the layout file to display the countdown, and then a Handler and Runnable object were created in the Activity. The Runnable implemented the logic to update the countdown every 1 second and update the TextView. The post() method of the Handler was called in the onCreate() method of the Activity to start the countdown, and the Runnable was removed in the onPause() method to stop the countdown.