CountDownTimer实现点击按钮倒计时

使用背景:

一个比较常见到的功能:app在注册或者是找回密码等操作时,需要获取短信验证码,在点击了获取短信验证码的按钮后,就会出现倒计时,按钮变成不可点击状态,当倒计时结束后,如果你没有获取到验证码,可以再次点击。这个功能可以通过官方提供的CountDownTimer来简单实现!

官方文档:

比较简单,直接给出了一个例子,就是实现了一个时间间隔为1秒,总时长3秒的倒计时任务:
new CountDownTimer(30000, 1000) {

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

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

实际使用:

new CountDownTimer(60100,1000) {
      public void onTick(long millisUntilFinished) {                     
sendPasswordButton.setText(millisUntilFinished / 1000 + "秒后重发");                       
sendPasswordButton.setEnabled(false);                           
sendPasswordButton.setBackground(mContext.getResources().getDrawable(R.drawable.round_button_login_sendtimer));                    }                  
 @Override                    
     public void onFinish() {                        
sendPasswordButton.setText("发送动态密码");                      
sendPasswordButton.setEnabled(true);           
sendPasswordButton.setBackground(mContext.getResources().getDrawable(R.drawable.round_button_login_sendnormal));}              
 }.start();




 
  

注意细节:

在设置总时长的时候最好在整秒数的基础上加一点,不然有可能会出现设置了8秒,但是直接从8秒到6、5、4...的现象,谨记!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值