參考:http://www.2cto.com/kf/201506/412668.html
近期在做一個商城項目,點擊Button獲取驗證碼是必不可少的,那麼如何實現倒計時效果呢?也是發愁了一番來到網上搜索一下看到一篇不錯的博文,照葫蘆畫瓢一步步下下來,也實現了想要的效果.現在做一下總結,將來可以方便翻着看看,有需要的小夥伴也可以看一下,如有錯誤之處或者更好的請指出,方便大家交流提高.廢話不多說,上乾貨.
上效果:
1.android開發第一步當然是佈局了,爲代碼清晰,只在主頁面佈局裏面布了一個Button:
<Button
android:text="點擊獲取驗證碼"
android:background="#f5f5"
android:id="@+id/btn_djs"
android:layout_width="match_parent"
android:layout_height="36dp"/>
2.複寫了倒計時這個類,設置一些自己需要的參數,代碼中都有詳細的註釋,根據自己的需要配置就ok了.
//複寫倒計時
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
//計時過程
@Override
public void onTick(long l) {
//防止計時過程中重複點擊
btn_djs.setClickable(false);
btn_djs.setText(l/1000+"s");
}
//計時完畢的方法
@Override
public void onFinish() {
//重新給Button設置文字
btn_djs.setText("重新獲取驗證碼");
//設置可點擊
btn_djs.setClickable(true);
}
}
3.查找Button這個控件,new出複寫的倒計時這個類,設置點擊事件觸發倒計時.
btn_djs = (Button) findViewById(R.id.btn_djs);
//new倒計時對象,總共的時間,每隔多少秒更新一次時間
final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000,1000);
//給Button設置點擊時間,觸發倒計時
btn_djs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myCountDownTimer.start();
}
});