使用 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. Pingback: Loterijen Overzicht

  2. Pingback: Ziektekostenverzekering vergelijken

  3. Pingback: sol partners curry

  4. Pingback: Sim only vergelijken

  5. Pingback: 实验设计

  6. 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

  7. Pingback: photographs

  8. Pingback: monticelli spa brianza

  9. Pingback: juegosfriv.one/

  10. Pingback: trump for children

  11. Pingback: Skrota bilen Göteborg

  12. Pingback: ben buyum

  13. Pingback: www.m88vnbet.com

  14. Pingback: 100 layer challenge gone wrong

  15. Pingback: Denver uber driver

  16. Pingback: download free

  17. Pingback: apps

  18. Pingback: chimney repair

  19. Pingback: http://papasalpormayor.cl

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

  21. Pingback: top to bottom home improvement company LLC

  22. Pingback: lawyers

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

  24. Pingback: buy jintropin

  25. Pingback: M88

  26. Pingback: ivf

  27. Pingback: dryer vent clean

  28. Pingback: pre contest cycle

  29. Pingback: joseph s r de saram

  30. Pingback: rhodium

  31. Pingback: joseph shihara rukshan de saram

  32. Pingback: anapolon balkan pharmaceuticals

  33. Pingback: economics tuition

  34. Pingback: para kazanmak

  35. Pingback: economics tuition

  36. Pingback: Trisha

  37. Pingback: synergize consulting

  38. Pingback: ankara escort

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

  40. Pingback: Trisha on Times of India

  41. Pingback: short term steroid side effects

  42. Pingback: Internet Services in Australia

  43. Pingback: social media management

  44. Pingback: venus factor

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

  46. 建议贝壳单词增加用户体验反馈一栏,同时建议在每个单词的后面增加发音。