网络中有很多这样的需求。自己记录下来,仅作后期查看的一个记录
布局文件创建按钮
<Button android:id="@+id/btn_code" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:textColor="@color/text_black" android:text="获取验证码" />
自定义的时间统计类继承CountDownTimer
public class TimeCount extends CountDownTimer { private Button btn_count; public TimeCount(long millisInFuture, long countDownInterval, Button btn_count) { super(millisInFuture, countDownInterval); this.btn_count = btn_count; } @Override public void onTick(long millisUntilFinished) { btn_count.setEnabled(false); btn_count.setText(millisUntilFinished / 1000 + "秒"); } @Override public void onFinish() { btn_count.setEnabled(true); btn_count.setText("获取验证码"); } }
activity的 oncreate中实例化
timeCount = new TimeCount(60000, 1000, btnCode);
在
public void onViewClicked(View view) 方法中调用
timeCount.start();
在点击登录的时候取消操作
//取消倒计时 timeCount.cancel(); timeCount.onFinish();