<span style="color:#ff0000;">可以直接设置相关数据(总显示时间,显示间隔)</span>
</pre><pre name="code" class="java">
public class CountDownButton extends Button {private int count;
private Button button;
public clickEvent mClickEvent;
private long millisInFuture;//总秒数
private long countDownInterval;//间隔时间
private Timer timer;
private TimerTask timerTask;
public CountDownButton(Context context) {
super(context);
}
public CountDownButton(final Context context, AttributeSet attrs) {
this(context, attrs, 0);
button = this;
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (count == (int) (millisInFuture / 1000)) {
start();
mClickEvent.buttonClick();
}
}
});
}
public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 点击事件需要加入的功能重构该函数即可
*/
public interface clickEvent {
public abstract void buttonClick();
}
public void setNumber(long millisInFuture1, long countDownInterval1) {
millisInFuture = millisInFuture1;
countDownInterval = countDownInterval1;
count = (int) (millisInFuture1 / 1000);
}
private Runnable timeCount = new Runnable() {
@Override
public void run() {
countTime();
}
};
private void countTime() {
count--;
button.setText(count + "秒后重发");
if (count <= 0) {
button.setEnabled(true);
button.setText("发送验证码");
timerTask.cancel();
timer.cancel();
timer = null;
timerTask = null;
}
}
/**
* 定时器开启方法
*/
private void start() {
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
button.post(timeCount);
}
};
timer.schedule(timerTask, 0, 1000);
}
/**
* 定时器取消方法
*/
public void cancel() {
if (timer != null) {
timerTask.cancel();
timer.cancel();
timer = null;
timerTask = null;
}
}
}
</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
写的不好的地方请见谅.