publicclassCountDownTimerUtilsextendsCountDownTimer{
//发送短信按钮
privateTextViewmTv;
/**
*
*@paramtextView
*view
*@parammillisInFuture
*倒计时长
*@paramcountDownInterval
*多长时间
*/
publicCountDownTimerUtils(TextViewtextView,longmillisInFuture,longcountDownInterval){
super(millisInFuture,countDownInterval);
this.mTv=textView;
}
@Override
publicvoidonTick(longmillisUntilFinished){
mTv.setEnabled(false);
mTv.setText(millisUntilFinished/1000+"后重发");
SpannableStringspannableString=newSpannableString(mTv.getText().toString());
ForegroundColorSpanforegroundColorSpan=newForegroundColorSpan(Color.RED);
/**
*publicvoidsetSpan(Objectwhat,intstart,intend,intflags){
*主要是start跟end,start是起始位置,无论中英文,都算一个。
*从0开始计算起。end是结束位置,所以处理的文字,包含开始位置,但不包含结束位置。
*/
spannableString.setSpan(foregroundColorSpan,0,2,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色
mTv.setText(spannableString);
}
@Override
publicvoidonFinish(){
mTv.setText("重新发送");
mTv.setEnabled(true);//重新获得点击
}
用法
//获取验证码
countDownTimer=newCountDownTimerUtils(register_captcha_tv,60000,1000);
countDownTimer.start();
@Override
protectedvoidonDestroy(){
super.onDestroy();
if(countDownTimer!=null)
countDownTimer.cancel();
}
}
本文详细介绍了一种基于Android的倒计时定时器实现方法,通过自定义CountDownTimer类,实现了短信验证码发送后的倒计时功能。文章展示了如何设置倒计时长度、更新UI显示剩余时间,并在倒计时结束后恢复按钮状态。
808

被折叠的 条评论
为什么被折叠?



