Android自带的倒计时CountDownTimer
CountDownTimer类介绍:
CountDownTimer类比较简单,总共就一个构造和4个方法。内部是通过handler实现。
CountDownTimer(long time,long interval):参数time是总时间,interval是间隔时间。
start():开始倒计时的方法。
cancel():取消倒计时的方法。
onTink(long time):抽象方法,每个间隔时间一到就会调用一次,需要自己实现。参数time是指剩下的时间。
onFinish():抽象方法,倒计时完成的方法。
CountDownTimer示例:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private MyCountDownTimer timer;
private final long TIME = 60 * 1000L;
private final long INTERVAL = 1000L;
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
if (time <= 59) {
textView.setText(String.format("倒计时开始 00:%02d", time));
} else {
textView.setText(String.format("倒计时开始 %02d:%02d", time / 60, time % 60));
}
}
@Override
public void onFinish() {
textView.setText("倒计时结束 00:00");
cancelTimer();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textView = (TextView) findViewById(R.id.tv);
startTimer();
}
public void start(View view) {
startTimer();
}
public void cancel(View view) {
textView.setText("倒计时结束 00:00");
cancelTimer();
}
/**
* 开始倒计时
*/
private void startTimer() {
if (timer == null) {
timer = new MyCountDownTimer(TIME, INTERVAL);
}
timer.start();
}
/**
* 取消倒计时
*/
private void cancelTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
cancelTimer();
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"
android:text="开始" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cancel"
android:text="结束" />
</LinearLayout>
截图: