转载请注明出处:https://blog.csdn.net/mythmayor/article/details/72842875
使用工具类MyCountDownTimer即可轻松搞定
1.MyCountDownTimer.class
import android.os.CountDownTimer;
import android.widget.Button;
/**
* Created by mythmayor on 2017/4/17.
*/
public class MyCountDownTimer extends CountDownTimer {
private Button mBtn;
private int mEnable;
private int mDisable;
/**
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receive
* {@link #onTick(long)} callbacks.
*/
public MyCountDownTimer(long millisInFuture, long countDownInterval, Button btn, int enable, int disable) {
super(millisInFuture, countDownInterval);
mBtn = btn;
mEnable = enable;
mDisable = disable;
}
//计时过程
@Override
public void onTick(long l) {
//防止计时过程中重复点击
mBtn.setClickable(false);
mBtn.setText(l / 1000 + "s");
//设置按钮背景色
mBtn.setBackgroundResource(mDisable);
}
//计时完毕的方法
@Override
public void onFinish() {
//重新给Button设置文字
mBtn.setText("重新获取验证码");
//设置可点击
mBtn.setClickable(true);
//设置按钮背景色
mBtn.setBackgroundResource(mEnable);
}
}
2.MyCountDownTimer的使用
private MyCountDownTimer mTimer;
//new倒计时对象,总共的时间,每隔多少秒更新一次时间
mTimer = new MyCountDownTimer(60000, 1000, button, R.drawable.bg1, R.drawable.bg2);
mTimer.start();
//获取验证码失败,显示重新获取验证码
if (mTimer != null) {
mTimer.cancel();
mTimer.onFinish();
}