布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="倒计时" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="A" />
</LinearLayout>
MyCountDownTimer 内部类
private class MyCountDownTimer extends CountDownTimer {//获取验证码倒计时功能
private MyCountDownTimer(long millisInFuture, long countDownInterval) {// 参数依次为总时长,和计时的时间间隔
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {// 计时过程显示
String Second = millisUntilFinished / 1000 + "S";
tv_time.setText(Second);
tv_time.setOnClickListener(null);
}
@Override
public void onFinish() {//计时完毕时触发
tv_time.setText("点击获取验证码");
tv_time.setOnClickListener(MainActivity.this);
}
}
OnCreate()实例化
private MyCountDownTimer myCountDownTimer;
调用
@Override
public void onClick(View v) {
//开始倒计时
myCountDownTimer.start();
}