首先创建一个类 放在工具包中
import android.os.CountDownTimer;
import android.widget.Button;
public class CountDownButtonUtils {
private CountDownTimer countDownTimer;
private OnFinishListener listener;
private Button button;
public CountDownButtonUtils(final Button button,
final String defaultString, int max, int interval) {
this.button = button;
if (max == 0 && interval == 0) {
button.setText(defaultString);
return;
}
countDownTimer = new CountDownTimer(max * 1000, interval * 1000 - 10) {
@Override
public void onTick(long time) {
button.setText("(" + ((time + 15) / 1000) + "秒)"
+ defaultString);
}
@Override
public void onFinish() {
button.setEnabled(true);
button.setText(defaultString);
if (listener != null) {
listener.finish();
}
}
};
}
public void start() {
button.setEnabled(false);
countDownTimer.start();
}
/**
* 关闭倒计时,不可点击
*/
public void cancel(boolean isEnabled) {
countDownTimer.cancel();
if (isEnabled) {
button.setEnabled(isEnabled);
}
}
public void setOnFinishListener(OnFinishListener listener) {
this.listener = listener;
}
public interface OnFinishListener {
public void finish();
}
}
然后 当那个button需要倒计时时 实例化这个类 类.start();开始倒计时