使用 CountDownTimer 类实现获取验证码的按钮

今天群里有人问:“有人用过类似这样的库吗?就是发送验证码,然后按钮会自动倒数60秒后才可以点击”,结果他就被踢了……额。 且不说伸手党的问题,也不说自己用线程或手动去做出这么一个 View ,就说当时底下有人回复:“Android 官方有提供 CountDownTimer 类”,而我本来也不知道有这个类,于是去查了下官方文档:

发现这真是一个很好用的类,能够定制一个倒计时,并且在倒计时的过程和结束时,分别有对应的回调方法。简单好用,于是我照着官方提供的例子代码,修改了一下,实现了这个获取验证码的按钮,效果如下:


实际代码很简单,我也就不多说了,直接看一下就懂了:

mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new CountDownTimer(10000, 1000) {
            // 第一个参数是总的倒计时时间
            // 第二个参数是每隔多少时间(ms)调用一次onTick()方法
            public void onTick(long millisUntilFinished) {
                mButton.setText(millisUntilFinished / 1000 + "s后重新发送");
                mButton.setEnabled(false);
            }

            public void onFinish() {
                mButton.setText("重新获取验证码");
                mButton.setEnabled(true);
            }
        }.start();
    }
});
  1. 建议贝壳单词增加用户体验反馈一栏,同时建议在每个单词的后面增加发音。

  2. 不错哈哈。不过还有个问题要考虑,就是发送验证码以后,退出这个界面还是要保存验证码当前的倒数时间状态,不然再进去页面的时候又可以发送验证码了。

  3. Pingback: venus factor

  4. Pingback: social media management

  5. Pingback: Internet Services in Australia

  6. Pingback: short term steroid side effects

  7. Pingback: Trisha on Times of India

  8. Pingback: http://www.linhchitp.com Nấm linh chi

  9. Pingback: ankara escort

  10. Pingback: synergize consulting

  11. Pingback: Trisha

  12. Pingback: economics tuition

  13. Pingback: para kazanmak

  14. Pingback: economics tuition

  15. Pingback: anapolon balkan pharmaceuticals

  16. Pingback: joseph shihara rukshan de saram

  17. Pingback: rhodium

  18. Pingback: joseph s r de saram

  19. Pingback: pre contest cycle

  20. Pingback: dryer vent clean

  21. Pingback: ivf

  22. Pingback: M88

  23. Pingback: buy jintropin

  24. Pingback: http://britlock.com.au

  25. Pingback: lawyers

  26. Pingback: top to bottom home improvement company LLC

  27. Pingback: http://www.godwinsremovals.co.uk/international-removals/northern-ireland

  28. Pingback: http://papasalpormayor.cl

  29. Pingback: chimney repair

  30. Pingback: apps

  31. Pingback: download free

  32. Pingback: Denver uber driver

  33. Pingback: 100 layer challenge gone wrong

  34. Pingback: www.m88vnbet.com

  35. Pingback: ben buyum

  36. Pingback: Skrota bilen Göteborg

  37. Pingback: trump for children

  38. Pingback: juegosfriv.one/

  39. Pingback: monticelli spa brianza

  40. Pingback: photographs

  41. Pingback: Nonis café, nonis café,Places to eat in Birmingham al, nonis cafe birmingham al, nonis cafe menu,Best restaurants in Birmingham al,places to eat in 5 points south birmingham al,five points birmingham restaurants,restaurants in five points south birmingh

  42. Pingback: 实验设计