一、概述
項目中經常用到倒計時的功能:手機獲取驗證碼。google官方也幫我們封裝好了一個類:CountDownTimer,使我們的開發(fā)更加方便;
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 + "秒");
? ? ????}
????}
}