要點
1.通過計時器Timer TimerTask 設(shè)置每秒執(zhí)行一次遞減任務(wù)
2.通過handler 在UI線程中修改秒數(shù)
3.設(shè)置開關(guān)躏将,對Timer TimerTask 停止消除任務(wù)
4.設(shè)置初始按鈕樣式,和倒計時按鈕樣式侄旬。(自行設(shè)置)
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.Button;
import java.util.Timer;
import java.util.TimerTask;
/**
* 倒計時時間控件
*/
public class TimeButton extends Button {
private long length = 60 * 1000;// 倒計時長度,這里給了默認(rèn)60秒
private String text_after = "s";
private String text_before = "獲取驗證碼";
private Timer timer;
private TimerTask timerTask;
private long time;
public TimeButton(Context context) {
super(context);
}
public TimeButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimeButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 倒計時
*/
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
TimeButton.this.setText(time / 1000 + text_after);
time -= 1000;
if (time < 0) {
TimeButton.this.setEnabled(true);
TimeButton.this.setText(text_before);
clearTimer();
}
}
};
private void initTimer() {
time = length;
if(timer==null) {
timer = new Timer();
}
if(timerTask==null) {
timerTask = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0x01);
}
};
}
}
private void clearTimer() {
try {
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
//還原樣式
setBackgroundResource(R.drawable.shape_btn_round_corner_orange);
setTextColor(getResources().getColor(R.color.common_background_white));
}catch (Exception e){
}
}
/**
* 開始倒計時
*/
public void start_count_down(){
this.setEnabled(false);
initTimer();
timer.schedule(timerTask, 0, 1000);
//設(shè)置倒計時樣式
setBackgroundResource(R.drawable.shape_common_radius_corner_line);
setTextColor(getResources().getColor(R.color.common_top_bar_color_in_orange));
}
/**
* 停止倒計時
*/
public void stop_count_down(){
clearTimer();
}
/**
* 設(shè)置到計時長度
*
* @param length
* 時間 默認(rèn)毫秒
* @return
*/
public TimeButton setLength(long length) {
this.length = length;
return this;
}
}