手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >Android使用CountDownTimer实现倒计时效果
Android使用CountDownTimer实现倒计时效果
摘要:在开发中会经常用到倒计时这个功能,包括给手机发送验证码等等,之前我的做法都是使用Handler+Timer+TimerTask来实现,现在发...

在开发中会经常用到倒计时这个功能,包括给手机发送验证码等等,之前我的做法都是使用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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持查字典教程网。

【Android使用CountDownTimer实现倒计时效果】相关文章:

Android使用Pull解析器解析xml文件的实现代码

android 之Spinner下拉菜单实现级联

Android HTTP 实现与服务器通信

Android 使用XML做动画UI的深入解析

Android实现屏幕旋转方法总结

Android补间动画效果

Android上使用jspf插件框架的方法

基于Android中实现定时器的3种解决方法

Android中实现动态切换组件背景的操作

android Watchdog 实现剖析

精品推荐
分类导航