天天看點

CountDownTimer實作點選按鈕倒計時

使用背景:

一個比較常見到的功能:app在注冊或者是找回密碼等操作時,需要擷取短信驗證碼,在點選了擷取短信驗證碼的按鈕後,就會出現倒計時,按鈕變成不可點選狀态,當倒計時結束後,如果你沒有擷取到驗證碼,可以再次點選。這個功能可以通過官方提供的CountDownTimer來簡單實作!

官方文檔:

http://developer.android.com/reference/android/os/CountDownTimer.html

比較簡單,直接給出了一個例子,就是實作了一個時間間隔為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...的現象,謹記!