温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Android中实现倒计时功能

发布时间:2021-05-27 17:49:27 来源:亿速云 阅读:116 作者:Leah 栏目:移动开发

如何在Android中实现倒计时功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

CountDownTimer 实现倒计时功能的机制也是用Handler 消息控制,只是它帮我们已经封装好了,先看一下它的介绍。

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText(“done!”);
}
}.start();

大致意思是,设置一个倒计时,直到完成这个时间段的计时,并会实时更新时间的变化,最后举了一个30秒倒计时的例子,如下:

 new CountDownTimer(30000, 1000) {
   public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
   }
   public void onFinish() {
     mTextField.setText("done!");
   }
 }.start();

详解

可以看到,上面示例中构造方法需要传入两个参数,如下:

 /**
 * @param millisInFuture The number of millis in the future from the call to start()
 *           until the countdown is done and onFinish() is called.
 * @param countDownInterval The interval along the way to receive onTick(long) callbacks.
 */
 public CountDownTimer(long millisInFuture, long countDownInterval) {
   mMillisInFuture = millisInFuture;
   mCountdownInterval = countDownInterval;
 }

第一个参数是倒计时的总时间,第二个参数是倒计时的时间间隔(每隔多久执行一次),注意这里传入的两个时间参数的单位都是毫秒。

它提供的几个方法也很简单,如下:

如何在Android中实现倒计时功能

  • start():开始倒计时。

  • cancel():取消倒计时。

  • onFinish():倒计时完成后回调。

  • onTick(long millisUnitilFinished):当前任务每完成一次倒计时间隔时间时回调。

验证码示例

短信验证码倒计时原理很简单,也就是点击获取验证码开启倒计时,在倒计时内不可点击,倒计时结束后方可重新获取,如下所示:

new CountDownTimer(millisUntilFinished, 1000) {
  /**
   * 当前任务每完成一次倒计时间隔时间时回调
   * @param millisUntilFinished
   */
  public void onTick(long millisUntilFinished) {
    if (btn_Code != null) {
      //按钮不可用
      btn_Code.setClickable(false);
      btn_Code.setEnabled(false);
      btn_Code.setText(millisUntilFinished / 1000 + "s");
    }
  }

  /**
   * 倒计时完成后回调
   */
  public void onFinish() {
    if (btn_Code != null) {
      //按钮可用
      btn_Code.setText("重新获取");
      btn_Code.setClickable(true);
      btn_Code.setEnabled(true);
    }
    //取消倒计时
    cancel();
  }
}.start();

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI