当前位置: 移动技术网 > IT编程>移动开发>Android > Android使用CountDownTimer实现倒计时效果

Android使用CountDownTimer实现倒计时效果

2019年07月24日  | 移动技术网IT编程  | 我要评论

美食的俘虏148什么时候出,三二七八影视,三洋微波炉怎么样

在开发中会经常用到倒计时这个功能,包括给手机发送验证码等等,之前我的做法都是使用handler + timer + timertask来实现,现在发现了这个类,果断抛弃之前的做法,相信还是有很多人和我一样一开始不知道android已经帮我们封装好了一个叫countdowntimer的类。

从字面上就可以看出来它叫倒数计时器又称定时器或计时器,采用handler的方式实现,将后台线程的创建和handler队列封装而成。
看了一下源码,发现这个类的调用还蛮简单,只有四个方法:

(1)public abstract void ontick(long millisuntilfinished);
固定间隔被调用

(2)public abstract void onfinish();
倒计时完成时被调用

(3)public synchronized final void cancel():
取消倒计时,当再次启动会重新开始倒计时

(4)public synchronized final countdowntimer start():
启动倒计时

在这里可以看到前面两个是抽象方法,需要重写。

简单看一下代码:

package com.per.countdowntimer;

import android.app.activity;
import android.os.bundle;
import android.os.countdowntimer;
import android.view.view;
import android.widget.textview;


public class mainactivity extends activity {
 private textview mtvshow;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  mtvshow = (textview) findviewbyid(r.id.show);
 }

 /**
  * 取消倒计时
  * @param v
  */
 public void oncancel(view v) {
  timer.cancel();
 }

 /**
  * 开始倒计时
  * @param v
  */
 public void restart(view v) {
  timer.start();
 }

 private countdowntimer timer = new countdowntimer(10000, 1000) {

  @override
  public void ontick(long millisuntilfinished) {
   mtvshow.settext((millisuntilfinished / 1000) + "秒后可重发");
  }

  @override
  public void onfinish() {
   mtvshow.setenabled(true);
   mtvshow.settext("获取验证码");
  }
 };
}

顺带附上xml布局文件

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/white"
 android:orientation="vertical"
 android:padding="16dp">

 <textview
  android:id="@+id/show"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/hello_world" />

 <button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_margintop="10dp"
  android:onclick="restart"
  android:text="取消" />

 <button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_margintop="10dp"
  android:onclick="oncancel"
  android:text="结束" />

</linearlayout>

最后说明一下:
countdowntimer timer = new countdowntimer(10000, 1000):以毫秒为单位,第一个参数是指从开始调用start()方法到倒计时完成的时候onfinish()方法被调用这段时间的毫秒数,也就是倒计时总的时间;第二个参数表示间隔多少毫秒调用一次 ontick方法,例如间隔1000毫秒。
在调用的时候直接使用timer.start();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网