?????? 本人目前Android小白一枚齿拂,目前正在實習(xí),因為在項目中用到的東西過段時間后經(jīng)常會忘肴敛,所以決定在簡書記錄一下署海,方便以后查閱。若有說的不對的地方医男,歡迎各位大佬指正砸狞,小弟會虛心學(xué)習(xí)。
目前公司項目中有好幾個用到倒計時的功能就找方法做了一個镀梭。
先上效果圖:
當(dāng)點擊獲取驗證碼時按鈕開始60秒倒計時刀森,當(dāng)?shù)褂嫊r完成后,按鈕變?yōu)椤爸匦芦@取驗證碼”报账。
接下來上代碼:
先上Button的布局文件
? ? ? ? ? android:id="@+id/get_code"
? ? ? ? ? android:layout_width="100dp"
? ? ? ? ? android:layout_height="35dp"
? ? ? ? ? android:layout_marginRight="15dp"
? ? ? ? ? android:background="@drawable/selector_verify_code"?? //這個是自定義的背景研底,就不詳細(xì)寫了
? ? ? ? ? android:padding="10dp"
? ? ? ? ? android:text="獲取驗證碼"
? ? ? ? ? android:textColor="@color/blue"
? ? ? ? ? android:textSize="10dp"/>
Android中提供了一個CountDownTimer 的倒計的類,初始化這個類的時候會重寫兩個方法透罢,一個是?onTick() 榜晦,另一個是onFinish()。第一個方法開始計時的時候調(diào)用琐凭,可以在里面動態(tài)的改變計時的數(shù)字芽隆,第二個方法在計時完成時調(diào)用浊服,可以在里面添加計時完成后需要改變的UI统屈。
在代碼中添加倒計時:
CountDownTimer? timer =new CountDownTimer (60*1000,1000) {
??????? @Override
? ????? public void onTick (long millisUntilFinished)? {
?????????????? button.setEnabled (false);
? ? ? ? ? ? ?? button.setBackground(getResources().getDrawable(R.drawable.selector_code_get));
? ? ? ? ? ? ?? button.setText("" + millisUntilFinished /1000);
? ? }
????? @Override
? ? ?? public void onFinish() {
????????????? button.setEnabled(true);
? ? ? ??????? button.setBackground(getResources().getDrawable(R.drawable.selector_verify_code));
? ? ? ? ? ??? button.setText(“重新獲取驗證碼”);
? ? }
}.start();