本文通过CountDownTimer来实现倒计时的功能,先上效果图
1.核心方法就是通过onTick方法来获取时间的改变
public void onTick(long millisUntilFinished) {
//计时过程显示
this.millisUntilFinished = millisUntilFinished;
button.setTextColor(Color.parseColor("#FFFFFF"));
button.setClickable(false);
button.setTextSize((float) 11.5);
DecimalFormat dec = new DecimalFormat("##.##");
button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");
}
其中Math.floor(millisUntilFinished / 60000)是通过毫秒数获取分钟,
dec.format((millisUntilFinished % 60000) / 1000)是对当前毫秒数取余获取出去分钟后的秒数,保留2位
以下是完整代码
package com.shangshaban.zhaopin.utils;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.widget.TextView;
import java.text.DecimalFormat;
/**
* 作者: 宋正朋 on 2016/6/18.
* 发送验证码后的倒计时
*/
public class PeterTimeCountRefresh extends CountDownTimer {
private TextView button;
private long millisUntilFinished;
public PeterTimeCountRefresh(long millisInFuture, long countDownInterval, final TextView button) {
super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔,要显示的按钮
this.button = button;
}
@Override
public void onTick(long millisUntilFinished) {//计时过程显示
this.millisUntilFinished = millisUntilFinished;
button.setTextColor(Color.parseColor("#FFFFFF"));
//button.setBackgroundResource(R.drawable.send_code_wait);
button.setClickable(false);
button.setTextSize((float) 11.5);
DecimalFormat dec = new DecimalFormat("##.##");
button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");
}
@Override
public void onFinish() {//计时完毕时触发
button.setText("刷新");
button.setTextColor(Color.parseColor("#FFFFFF"));
// button.setBackgroundResource(R.drawable.send_code);
button.setClickable(true);
}
}
2.在Activity中的使用
PeterTimeCountRefresh timer = new PeterTimeCountRefresh(600000, 1000, btnRefresh);
timer.start();
3.最后,在onDestroy中关掉计时器,防止内存泄漏
@Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
}
OK,搞定!