发布于 2017-09-18 11:03:57 | 109 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要为大家详细介绍了Android使用CountDownTimer实现倒计时效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务