国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android實現倒計時CountDownTimer使用詳解

2019-10-22 18:18:20
字體:
來源:轉載
供稿:網友

在開發中會經常用到倒計時這個功能,包括給手機發送驗證碼等等,之前我的做法都是使用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();

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 娱乐| 类乌齐县| 宣汉县| 西乌珠穆沁旗| 岱山县| 丰原市| 霍林郭勒市| 连山| 延庆县| 二连浩特市| 德阳市| 沙坪坝区| 德昌县| 明光市| 平湖市| 灌南县| 吉木萨尔县| 文化| 平舆县| 乌兰浩特市| 塔城市| 邹城市| 潢川县| 五台县| 公主岭市| 南昌市| 翁牛特旗| 东阳市| 弋阳县| 汶上县| 吴江市| 通河县| 尼勒克县| 大荔县| 厦门市| 井研县| 高碑店市| 南平市| 启东市| 明光市| 浙江省|