Android - 验证码发送倒计时效果

转载请注明出处:https://blog.csdn.net/mythmayor/article/details/72842875

使用工具类MyCountDownTimer即可轻松搞定

1.MyCountDownTimer.class

import android.os.CountDownTimer;
import android.widget.Button;

/**
 * Created by mythmayor on 2017/4/17.
 */

public class MyCountDownTimer extends CountDownTimer {
    private Button mBtn;
    private int mEnable;
    private int mDisable;

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public MyCountDownTimer(long millisInFuture, long countDownInterval, Button btn, int enable, int disable) {
        super(millisInFuture, countDownInterval);
        mBtn = btn;
        mEnable = enable;
        mDisable = disable;
    }

    //计时过程
    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        mBtn.setClickable(false);
        mBtn.setText(l / 1000 + "s");
        //设置按钮背景色
        mBtn.setBackgroundResource(mDisable);
    }

    //计时完毕的方法
    @Override
    public void onFinish() {
        //重新给Button设置文字
        mBtn.setText("重新获取验证码");
        //设置可点击
        mBtn.setClickable(true);
        //设置按钮背景色
        mBtn.setBackgroundResource(mEnable);
    }
}

2.MyCountDownTimer的使用

private MyCountDownTimer mTimer;

//new倒计时对象,总共的时间,每隔多少秒更新一次时间
mTimer = new MyCountDownTimer(60000, 1000, button, R.drawable.bg1, R.drawable.bg2);
mTimer.start();

//获取验证码失败,显示重新获取验证码
if (mTimer != null) {
    mTimer.cancel();
    mTimer.onFinish();
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值