Android实现验证码倒计时控件

CountDownTimer原理分析

实现倒计时相关计时功能Android官方API中给出了CountDownTimer这个类专门用于实现倒计时功能的。其简单的使用如

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }
     public void onFinish() {
        mTextField.setText("done!");
     }
    }.start();

该计时器采用毫秒的方式计算,最基本的原理还是采用的是Android的老熟人Handler实现异步通信更新控件的。不多说贴出源码看看:

private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized (CountDownTimer.this) {
                if (mCancelled) {
                    return;
                }

                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

                if (millisLeft <= 0) {
                    onFinish();
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    // take into account user's onTick taking time to execute
                    long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
                    long delay;

                    if (millisLeft < mCountdownInterval) {
                        // just delay until done
                        delay = millisLeft - lastTickDuration;

                        // special case: user's onTick took more than interval to
                        // complete, trigger onFinish without delay
                        if (delay < 0) delay = 0;
                    } else {
                        delay = mCountdownInterval - lastTickDuration;

                        // special case: user's onTick took more than interval to
                        // complete, skip to next interval
                        while (delay < 0) delay += mCountdownInterval;
                    }

                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };

从源码看出在异步通信循环中实现了几个关键方法,也就是我们自定义倒计时控件所必须的和注意的地方

自定义倒计时控件

要自定义验证码倒计时控件我们就需要继承与CountDownTimer类并实现相应的方法。闲话不多说上代码

public class CodeCount extends CountDownTimer {

    private Button button;

    /**
     * @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 CodeCount(Button btn, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        this.button = btn;
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //防止计时过程中重复点击
        button.setClickable(false);
        button.setText("" + millisUntilFinished / 1000 + "s");
        button.setBackgroundResource(R.drawable.valid_code_bg);
        button.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.colorWhite));
    }

    @Override
    public void onFinish() {
        //重新给Button设置文字
        button.setText("重新获取验证码");
        //设置可点击
        button.setClickable(true);
        button.setBackgroundResource(R.drawable.code_btn_bg);
        button.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.colorAccent));
    }

以上就是自定义的倒计时控件啦,在需要倒计时功能的地方直接使用就行啦,不过从Android源码中我们会发现采用Handler进行异步通信易发生内存泄漏问题,不过官方也给出了相应的回收方法cancel()啦,只需要在使用时注意下就行~~

自定义控件的简单使用

 CodeCount count = new CodeCount(btnCode, 60000, 1000);
 count.start();

为防止内存泄漏问题在页面回收时调用对应的回收方法


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (count != null) {
            count.cancel();
        }
    }

关于倒计时控件的简单实现和注意就分享到这里啦,本人一个入坑的小白,欢迎砖家门吐槽和鼓励,同时也希望能够给你带来一点点小帮助~~~3Q

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,068评论 25 709
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 47,104评论 22 665
  • 最近在备考,因为是毕业后的第一年,所以总感觉有点力不从心,每次回来就想呼呼大睡,但是深夜醒来又捶胸顿足,后悔不已。...
    伊砢珈阅读 330评论 0 0
  • 看到这个征文,我在脑子里搜刮了与母亲有关的所有记忆,却发现没有任何一种花与母亲有关,能够很贴切的形容母亲。然,我所...
    九空阅读 685评论 6 5
  • 总是很天真的认为,什么事情都可以自己解决,可是当你偶然看到那些情侣之间做的小动作,那种保护的动作,总是内心突然坍塌...
    疯女纸阅读 173评论 0 1

友情链接更多精彩内容