实现一个简单的计时器

来源:互联网 发布:电脑游戏多开器 端口 编辑:程序博客网 时间:2024/05/19 19:41

        项目开发过程中经常会遇到这样的需求:让用户输入手机号,点击获取验证码,然后开始倒计时。所以就写了一个简单的计时器。

1.先看效果:

        

        2.实现思路:定义一个类CountDownTimerImpl继承自CountDownTimer类, 重写父类的onTick()与onFinish()方法,分别表示开始计时与计时结束。开始计时 改变控件状   态,计时结束恢复控件初始状态。代码如下:

public class CountDownTimerImpl extends CountDownTimer {    private TextView mTextView;    /**     * @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 receive     *                          {@link #onTick(long)} callbacks.     */    public CountDownTimerImpl(long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);    }    @Override    public void onTick(long millisUntilFinished) {        mTextView.setClickable(false);//开始计时设置按钮不可点击        mTextView.setText(millisUntilFinished/1000+"秒后可重新发送");        mTextView.setBackgroundResource(R.drawable.tv_code_press);        //设置时间为红色,        String text = mTextView.getText().toString();        SpannableString spannableString=new SpannableString(text);        ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);        String substring = text.substring(0, 2);        if (isNumeric(substring)){            spannableString.setSpan(span,0,2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);        }else {            spannableString.setSpan(span,0,1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);        }        mTextView.setText(spannableString);    }    @Override    public void onFinish() {        mTextView.setText("获取验证码");        mTextView.setClickable(true);        mTextView.setBackgroundResource(R.drawable.tv_code_nomol);    }    public CountDownTimerImpl(long millisInFuture, long countDownInterval, TextView textView) {        super(millisInFuture, countDownInterval);        mTextView = textView;    }    /**     * 判断字符串是否为数字     * @param str     * @return     */    private  boolean isNumeric(String str){        for (int i = 0; i < str.length(); i++){            System.out.println(str.charAt(i));            if (!Character.isDigit(str.charAt(i))){                return false;            }        }        return true;    }}
       3.使用:

 mTextView= (TextView) findViewById(R.id.tv_getSecurityCode);        mTextView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mCountDownTimer=new CountDownTimerImpl(60000,1000,mTextView);                mCountDownTimer.start();            }        });

4.查看demo

原创粉丝点击