你还在用Handler+Timer来实现倒计时吗?
以前实现倒计时都是使用Handler+Timer,今天介绍一个更简单的方法。
主要就是用CountDownTimer类来实现。
其实很简单,没什么可说的,上代码。
以获取验证码时倒计时为例。
public class TimerCount extends CountDownTimer
{
Button button;
Context context;
/**
* @param millisInFuture
* 计时总时间
* @param countDownInterval
* 时间间隔
* @param button
* 用于显示时间的view,这里是我加上的
*/
public TimerCount(long millisInFuture, long countDownInterval, Button button, Context context)
{
super(millisInFuture, countDownInterval);
this.button = button;
this.context = context;
}
@Override
public void onFinish()
{
button.setText(R.string.get_code_again);
button.setTextColor(context.getResources().getColor(R.color.txt_color_blue));
button.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished)
{
button.setClickable(false);
button.setTextColor(context.getResources().getColor(R.color.gray));
button.setText("重新获取(" + millisUntilFinished / 1000 + "秒)");
}
}
很简单吧,构造方法中的Button和Context都是我自己加上的,Context可以不需要,因为下面是引用资源文件才用到的。
Button的传入显示计时剩下的时间。
至于使用吗,就更简单的,直接new一个对象,然后start就OK了,也不需要stop,它自己都处理了。取消或者中断计时也有cancel方法。
是不是很简单。。。