以下代码直接复制就可以使用了
首页给他button 设置一个背景选择器
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/auth_code_pressed" android:state_pressed="true"></item> <item android:drawable="@drawable/auth_code_pressed" android:state_selected="true"></item> <item android:drawable="@drawable/auth_code_pressed" android:state_enabled="false"></item> <item android:drawable="@drawable/auth_code_normal"></item> </selector>第二步创建一个类 将以下代码复制
public class CountDownButton { // 倒计时timer private CountDownTimer countDownTimer; // 计时结束的回调接口 private OnFinishListener listener; private Button button; /** * * @param button * 需要显示倒计时的Button * @param defaultString * 默认显示的字符串 * @param max * 需要进行倒计时的最大值,单位是秒 * @param interval * 倒计时的间隔,单位是秒 */ public CountDownButton(final Button button, final String defaultString, int max, int interval) { this.button = button; // 由于CountDownTimer并不是准确计时,在onTick方法调用的时候,time会有1-10ms左右的误差,这会导致最后一秒不会调用onTick() // 因此,设置间隔的时候,默认减去了10ms,从而减去误差。 // 经过以上的微调,最后一秒的显示时间会由于10ms延迟的积累,导致显示时间比1s长max*10ms的时间,其他时间的显示正常,总时间正常 countDownTimer = new CountDownTimer(max * 1000, interval * 1000 - 10) { @Override public void onTick(long time) { // 第一次调用会有1-10ms的误差,因此需要+15ms,防止第一个数不显示,第二个数显示2s button.setText(defaultString + "(" + ((time + 15) / 1000) + "秒)"); Log.d("CountDownButtonHelper", "time = " + (time) + " text = " + ((time + 15) / 1000)); } @Override public void onFinish() { button.setEnabled(true); button.setText(defaultString); if (listener != null) { listener.finish(); } } }; } /** * 开始倒计时 */ public void start() { button.setEnabled(false); countDownTimer.start(); } /** * 设置倒计时结束的监听器 * * @param listener */ public void setOnFinishListener(OnFinishListener listener) { this.listener = listener; } /** * 计时结束的回调接口 * * @author zhaokaiqiang * */ public interface OnFinishListener { public void finish(); } }第三步 用法
@OnClick({R.id.but_obtain_code}) public void onClick(View v) { switch (v.getId()) { case R.id.but_obtain_code: //获取验证码 设置1.button控件 2.显示文字 //3.计时几秒 4.间隔时间 CountDownButton helper=new CountDownButton(mObtainCode,"重新获取",60,1); helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() { //倒计时结束回调 @Override public void finish() { Toast.makeText(base,"呵呵",Toast.LENGTH_SHORT).show(); } }); //开始计时 helper.start(); break; } }