您的位置:首页 > 移动开发 > Android开发

Android短信倒计时功能的实现

2017-06-12 11:52 302 查看
开发一个app  经常会有获取短信验证码的需求  由于短信的延时 也为了安全以及用户体验 经常会给发送短信验证 发送 请求之后  加一个倒计时的功能  好了 废话停止 先上效果图''''''首先需要自定义一个类 CountDownTimerUtils继承CountDownTimer 下面是实现代码
package com.sunking.mockingbot.Utils;import android.graphics.Color;import android.os.CountDownTimer;import android.text.SpannableString;import android.widget.TextView;import com.sunking.mockingbot.R;/*** Created by ITBOY on 2017/6/9 0009.***/public class CountDownTimerUtils extends CountDownTimer {private TextView mTextView;/*** @param textView          The TextView*** @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 receiver*                          {@link #onTick(long)} callbacks.*/public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);this.mTextView = textView;}@Overridepublic void onTick(long millisUntilFinished) {mTextView.setClickable(false); //设置不可点击mTextView.setText(millisUntilFinished / 1000 +"秒后重试");  //设置倒计时时间mTextView.setBackgroundResource(R.drawable.bg_identify_code_press); //设置按钮为灰色,这时是不能点击的SpannableString spannableString = new SpannableString(mTextView.getText().toString());  //获取按钮上的文字//将倒计时的时间设置为红色//这里会报数组越界异常 所以注释掉了   字体颜色 直接再下面设置/* ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);*//*** public void setSpan(Object what, int start, int end, int flags) {* 主要是start跟end,start是起始位置,无论中英文,都算一个。* 从0开始计算起。end是结束位置,所以处理的文字,包含开始位置,但不包含结束位置。*//*//spannableString.setSpan(span, 0, 2, Spannable.SPAN_COMPOSING);*/mTextView.setText(spannableString);mTextView.setTextColor(Color.RED);//在这里设置字体颜色  亲测  可用}@Overridepublic void onFinish() {mTextView.setTextColor(Color.WHITE);mTextView.setText("重新获取验证码");mTextView.setClickable(true);//重新获得点击mTextView.setBackgroundResource(R.drawable.bg_identify_code_normal);  //还原背景色}}
下面是如何调用
OK 到这里就结束了  如果遇到什么问题 欢迎下方  评论留言 乐于分享 共同进步!!!

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息