Android獲取短信驗證碼倒計時
目前越來越多的app在注冊或是進行對應操作時,要求獲取短信驗證碼,在點擊了獲取短信驗證碼的按鈕后,就是出現倒計時,比如倒計時120S,在倒計時 期間內,按鈕點擊是無效的,當倒計時結束后,如果你沒有獲取到驗證碼,可以再次點擊。實現倒計時的方法很多,我們今天就通過繼承 android. os.CountDownTimer類來實現!
首先看下我們封裝的倒計時工具類,主要為了在多個地方用到的話,用了多個構造方法,就是為了使用更靈活,只要傳入對數就可以調用了:
public class MyCountTimer extends CountDownTimer {
public static final int TIME_COUNT = 121000;//時間防止從119s開始顯示(以倒計時120s為例子)
private TextView btn;
private int endStrRid;
private int normalColor, timingColor;//未計時的文字顏色,計時期間的文字顏色
/**
* 參數 millisInFuture 倒計時總時間(如60S,120s等)
* 參數 countDownInterval 漸變時間(每次倒計1s)
* 參數 btn 點擊的按鈕(因為Button是TextView子類,為了通用我的參數設置為TextView)
* 參數 endStrRid 倒計時結束后,按鈕對應顯示的文字
*/
public MyCountTimer (long millisInFuture, long countDownInterval, TextView btn, int endStrRid) {
super(millisInFuture, countDownInterval);
this.btn = btn;
this.endStrRid = endStrRid;
}
/**
*參數上面有注釋
*/
public MyCountTimer (TextView btn, int endStrRid) {
super(TIME_COUNT, 1000);
this.btn = btn;
this.endStrRid = endStrRid;
}
public MyCountTimer (TextView btn) {
super(TIME_COUNT, 1000);
this.btn = btn;
this.endStrRid = R.string.txt_getMsgCode_validate;
}
public MyCountTimer (TextView tv_varify, int normalColor, int timingColor) {
this(tv_varify);
this.normalColor = normalColor;
this.timingColor = timingColor;
}
// 計時完畢時觸發
@Override
public void onFinish() {
if(normalColor > 0){
btn.setTextColor(normalColor);
}
btn.setText(endStrRid);
btn.setEnabled(true);
}
// 計時過程顯示
@Override
public void onTick(long millisUntilFinished) {
if(timingColor > 0){
btn.setTextColor(timingColor);
}
btn.setEnabled(false);
btn.setText(millisUntilFinished / 1000 + "s");
}
}
然后在你要實現倒計時的頁面用就可以了:
比如在AcvitityA中點擊倒時間的按鈕
Button smsBtn=findViewById(R.id.....);
MyCountTimertimeCount = new MyCountTimer(smsBtn, 0xfff30008, 0xff969696);//傳入了文字顏色值
timeCount.start();
如時你不傳入顏色值的話,也可以在點擊按鈕smsBtn的布局文件中根據按鈕狀態來設置顏色。
<Button
android:id="@+id/rebind_sms_btn"
android:layout_width="120dp"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@null"
android:gravity="center"
android:text="獲取短信驗證碼"
android:textColor="@color/hkb_binder_phone_text_color"
android:textSize="16sp" />
文字顏色對應的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#969696"/>
<item android:color="#f30008"/>
</selector>
本文由用戶 f663x 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!