English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation of CountDownTimer to Realize Countdown Timer Effect in Android

Implement the countdown effect

Example: Send verification code button

Illustration:

/**
 * Countdown
 * 
 * @author admin
 * 
 */
public class MainActivity extends ActionBarActivity {
  private Button tvTime;// Display time
  private MyCountDownTimer myCountDownTimer;// Countdown object
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvTime = (Button) findViewById(R.id.time);
    tvTime.setText("Send verification code");
    tvTime.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        start();
        tvTime.setEnabled(false);// The countdown timer is not clickable
      }
    });
  }
  /**
   * Start
   * 
   * @param view
   */
  public void start() {
    long countDownInterval = 1000;// Interval time
    long millisInFuture = 20000;// Duration
    myCountDownTimer = new MyCountDownTimer(millisInFuture,
        countDownInterval);
    myCountDownTimer.start();
  }
  /**
   * End
   * 
   * @param view
   */
  public void end() {
    if (myCountDownTimer != null) {
      myCountDownTimer.cancel();
    }
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    end();
  }
  /**
   * Countdown
   * 
   * @author admin
   * 
   */
  private class MyCountDownTimer extends CountDownTimer {
    public MyCountDownTimer(long millisInFuture, long countDownInterval) {
      super(millisInFuture, countDownInterval);
    }
    // Can directly update UI
    @Override
    public void onTick(long millisUntilFinished) {
      tvTime.setText("Remaining Time:") + millisUntilFinished / 1000);// Convert to seconds
    }
    @Override
    public void onFinish() {
      tvTime.setText("Get Verification Code");
      tvTime.setEnabled(true);// Click only when the time is up
    }
  }
}

That's all for this article, I hope it will be helpful to everyone's study, and I also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like