要点
1.通过计时器Timer TimerTask 设置每秒执行一次递减任务
2.通过handler 在UI线程中修改秒数
3.设置开关,对Timer TimerTask 停止消除任务
4.设置初始按钮样式,和倒计时按钮样式。(自行设置)
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;// 倒计时长度,这里给了默认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);
//设置倒计时样式
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();
}
/**
* 设置到计时长度
*
* @param length
* 时间 默认毫秒
* @return
*/
public TimeButton setLength(long length) {
this.length = length;
return this;
}
}