編輯:關於Android編程
在開發中會經常用到倒計時這個功能,包括給手機發送驗證碼等等,之前我的做法都是使用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();
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
ES文件浏覽器連接電腦顯示登錄失敗
ES文件浏覽器連接電腦顯示登錄失敗。之前在連著電腦看著電視,不知道手機怎麼了,現在連接不上,還顯示登錄失敗。現在不知道怎麼辦。小編來給大家演示一下,當ES浏
Android組件創建DrawerLayout導航
概述本篇博客是對developer.android.com/上的Training課程的簡單翻譯,若是覺得翻譯出來的理解有困難,請點擊下方鏈接查看原文!關於DrawerLa
android開發之synchronized的用法
android開發之synchronized的用法 在android開發中synchronized主要有四種用法。第一是在方法聲明時使用;第二是在對某一代碼塊時使用;
Android中ListView結合CheckBox實現數據批量選擇(全選、反選、全不選)
APP的開發中,會常遇到這樣的需求:批量取消(刪除)List中的數據。這就要求ListVIew支持批量選擇、全選、單選等等功能,做一個比較強大的ListView批量選擇功