android 倒計時CountDownTimer類的使用總結

一、概述

項目中經常用到倒計時的功能:手機獲取驗證碼。google官方也幫我們封裝好了一個類:CountDownTimer,使我們的開發(fā)更加方便;

二、API

CountDownTimer是一個抽象類,有兩個抽象方法,

1、public abstract void onTick(long millisUntilFinished);//這個是每次間隔指定時間的回調,millisUntilFinished:剩余的時間,單位毫秒

2、public abstract void onFinish();//這個是倒計時結束的回調

使用的時候只需要

new CountDownTimer(long millisInFuture, long countDownInterval)

//millisInFuture:倒計時的總時長

//countDownInterval:每次的間隔時間? 單位都是毫秒

三、基本使用方法

我們以短信驗證碼的倒計時來看,點擊獲取驗證碼,倒計時60s不可點擊

點擊按鈕,獲取驗證碼成功之后就可以執(zhí)行以上操作,最后一定要start,不然不會執(zhí)行

以按鈕為例實現(xiàn)手機獲取驗證碼舉例:

xml文件設置一個布局RelativeLayout

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_parent"

android:layout_marginTop="20dp"

android:layout_toLeftOf="@+id/btn" />

<Button

android:id="@+id/btn"

android:layout_width="100dp"

android:layout_height="wrap_parent"

android:layout_marginTop="20dp"

android:layout_alignParentRight="true"

android:text="獲取驗證碼" />

.java文件

public? class? MainActivity extends Activity{

? ? private Button mButtonClick;

? ??private TimerCount mTimerCount;

????@Override

????protected void onCreate(Bundle savedInstanceState) {

????????????super.onCreate(savedInstanceState);

? ? ? ? ? ? ?setContentView(R.layout.activity_main);

? ??????????mButtonClick = (Button )?findViewById(R.id.btn);

? ??????????mTimerCount = new??TimerCount (60 * 1000 , 1000);

? ??????????mButtonClick?.setOnClickListener(new View.OnClickListener() {

????????????????@Override

? ????????????????? public void onClick(View view) {

? ??????????????????????mTimerCount.start();

????????????????????}

????????????});? ? ? ? ? ? ? ?

????}

class??TimerCount? extends??CountDownTimer(){ //抽象類

//構造方法

? ? ? ? public??TimerCount (long totalTime, long interval){

? ? ? ? ? ? ? ? super(totalTime,interval);

? ? ? ?????}

????????@Override //覆寫方法 - 結束方法

? ???? public void onFinish() {

????????mButtonClick .setEnable(true);

? ? ? ? ? ?mButtonClick .setText("重新獲取");

????????}

? ? ????@Override? ??//覆寫方法 - 計時方法

? ??????public void onTick(long millisUntilFinished) {

? ??????mButtonClick .setEnable(false);

????????mButtonClick .setText(millisUntilFinished / 1000 + "秒");

? ? ????}

????}

}

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容