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

首頁 > OS > 安卓 > 正文

Android 簡單實現倒計時功能

2024-09-11 17:15:21
字體:
來源:轉載
供稿:網友

在 Android 中倒計時功能是比較常用的一個功能,比如短信驗證碼,付款倒計時等。實現方式有Handler、Thread 等,但是實現起來都有點麻煩,其實Android已經為我們封裝好了一個抽象類 CountDownTimer,可以簡單的實現倒計時功能,如下圖所示。

countDown.gif

CountDownTimer 實現倒計時功能的機制也是用Handler 消息控制,只是它幫我們已經封裝好了,先看一下它的介紹。

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:new CountDownTimer(30000, 1000) {public void onTick(long millisUntilFinished) {mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);}public void onFinish() {mTextField.setText(“done!”);}}.start();

大致意思是,設置一個倒計時,直到完成這個時間段的計時,并會實時更新時間的變化,最后舉了一個30秒倒計時的例子,如下:

 new CountDownTimer(30000, 1000) {   public void onTick(long millisUntilFinished) {     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);   }   public void onFinish() {     mTextField.setText("done!");   } }.start();

詳解

可以看到,上面示例中構造方法需要傳入兩個參數,如下:

 /** * @param millisInFuture The number of millis in the future from the call to start() *           until the countdown is done and onFinish() is called. * @param countDownInterval The interval along the way to receive onTick(long) callbacks. */ public CountDownTimer(long millisInFuture, long countDownInterval) {   mMillisInFuture = millisInFuture;   mCountdownInterval = countDownInterval; }

第一個參數是倒計時的總時間,第二個參數是倒計時的時間間隔(每隔多久執行一次),注意這里傳入的兩個時間參數的單位都是毫秒。

它提供的幾個方法也很簡單,如下:

methods.png

start():開始倒計時。 cancel():取消倒計時。 onFinish():倒計時完成后回調。 onTick(long millisUnitilFinished):當前任務每完成一次倒計時間隔時間時回調。

驗證碼示例

短信驗證碼倒計時原理很簡單,也就是點擊獲取驗證碼開啟倒計時,在倒計時內不可點擊,倒計時結束后方可重新獲取,如下所示:

new CountDownTimer(millisUntilFinished, 1000) {  /**   * 當前任務每完成一次倒計時間隔時間時回調   * @param millisUntilFinished   */  public void onTick(long millisUntilFinished) {    if (btn_Code != null) {      //按鈕不可用      btn_Code.setClickable(false);      btn_Code.setEnabled(false);      btn_Code.setText(millisUntilFinished / 1000 + "s");    }  }  /**   * 倒計時完成后回調   */  public void onFinish() {    if (btn_Code != null) {      //按鈕可用      btn_Code.setText("重新獲取");      btn_Code.setClickable(true);      btn_Code.setEnabled(true);    }    //取消倒計時    cancel();  }}.start();

注:在Activity或Fragment銷毀的時候記得調用 cancle() 方法,否則它的 onTick() 方法還會繼續執行,容易造成內存泄漏。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 微博| 西青区| 洞口县| 剑阁县| 微山县| 山东省| 双城市| 革吉县| 尤溪县| 南宁市| 广汉市| 永善县| 项城市| 宣威市| 基隆市| 抚顺县| 乌兰察布市| 廉江市| 阿坝县| 德保县| 合川市| 长宁县| 秭归县| 肃南| 光泽县| 浪卡子县| 长治市| 吉林省| 招远市| 花垣县| 上饶县| 张家界市| 靖安县| 略阳县| 禹城市| 泰顺县| 荆门市| 莱州市| 贡嘎县| 宁国市| 灵川县|