倒计时效果实现
1、倒计时工具类的实现
public class CountDownTimerUtils extends CountDownTimer implements View.OnClickListener {
private static final String TAG = CountDownTimerUtils.class.getSimpleName();
//普通倒计时
public static int NORMAL = 1;
//首页登陆获取验证码
public static int VERIFICODE = 2;
//倒计时类型
private static int type = NORMAL;
private TextView mTextView;//用于显示倒计时数字,也可作为按钮使用
private boolean isCounting=false;
private IReacquireListener iReacquireListener;
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval, int setType) {
super(millisInFuture, countDownInterval);//倒计时长,回调#onTick方法间隔时间
type = setType;
mTextView = textView;
mTextView.setOnClickListener(this);
}
@Override
public void onTick(long millisUntilFinished) {
isCounting=true;
mTextView.setClickable(false);
int second= (int) (millisUntilFinished / 1000);
Log.i(TAG, "onTick: second= "+second);
mTextView.setText(String.format(mTextView.getResources().getString(R.string.unit_second), second + ""));
//如果设置验证码倒计时
if (type == VERIFICODE){
mTextView.setBackgroundResource(R.drawable.btn_pressed_background);
SpannableString spannableString = new SpannableString(mTextView.getText().toString());
ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#F0752B"));
spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色
mTextView.setText(spannableString);
}
Log.i(TAG, "onTick: isCounting= "+isCounting());
}
@Override
public void onFinish() {
isCounting = false;
//如果设置验证码倒计时
if (type == VERIFICODE){
mTextView.setText(R.string.reacquire_verify_code);
mTextView.setClickable(true);
mTextView.setBackgroundResource(R.drawable.btn_background_selector);
}else if (type == NORMAL){
mTextView.setText("");
}
Log.i(TAG, "onFinish: isCounting= "+isCounting());
}
@Override
public void onClick(View v) {
iReacquireListener.reacquire();
}
//重新获取验证码回调接口
public interface IReacquireListener{
void reacquire();
}
public void setReacquireListener(IReacquireListener listener){
iReacquireListener=listener;
}
public boolean isCounting(){
return isCounting;
}
}
2、在代码中的使用
CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(tvCounter, 60000, 1000, VERIFICODE);
//开始倒计时
countDownTimerUtils.start();
//结束倒计时
countDownTimerUtils.cancel();