android 倒計(jì)時(shí)CountDownTimer類(lèi)的使用總結(jié)

一、概述

項(xiàng)目中經(jīng)常用到倒計(jì)時(shí)的功能:手機(jī)獲取驗(yàn)證碼。google官方也幫我們封裝好了一個(gè)類(lèi):CountDownTimer,使我們的開(kāi)發(fā)更加方便;

二、API

CountDownTimer是一個(gè)抽象類(lèi),有兩個(gè)抽象方法,

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

2、public abstract void onFinish();//這個(gè)是倒計(jì)時(shí)結(jié)束的回調(diào)

使用的時(shí)候只需要

new CountDownTimer(long millisInFuture, long countDownInterval)

//millisInFuture:倒計(jì)時(shí)的總時(shí)長(zhǎng)

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

三、基本使用方法

我們以短信驗(yàn)證碼的倒計(jì)時(shí)來(lái)看,點(diǎn)擊獲取驗(yàn)證碼,倒計(jì)時(shí)60s不可點(diǎn)擊

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

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

xml文件設(shè)置一個(gè)布局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="獲取驗(yàn)證碼" />

.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(){ //抽象類(lèi)

//構(gòu)造方法

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

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

? ? ? ?????}

????????@Override //覆寫(xiě)方法 - 結(jié)束方法

? ???? public void onFinish() {

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

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

????????}

? ? ????@Override? ??//覆寫(xiě)方法 - 計(jì)時(shí)方法

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

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

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

? ? ????}

????}

}

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

友情鏈接更多精彩內(nèi)容