使用CountDownTimer类实现倒计时功能

现在很多app都有发送短信验证的功能,在用户点击按钮发送验证码以后,就会再按钮上显示倒计时,在此期间点击按钮是无效的,在倒计时完成以后可以再次点击,我通过集成CountDownTimer来实现这个功能。

封装工具类

public class MyCountDownTimer extends CountDownTimer {
    private Button btn;
    private String msg;

    /**
     * 
     * @param millisInFuture
     *            倒计时总时间
     * @param countDownInterval
     *            间隔时间
     * @param button
     *            点击的空间,这里用Button
     * @param msg
     *            倒计时完成以后显示的文字
     */
    public MyCountDownTimer(long millisInFuture, long countDownInterval,
            Button button, String msg) {
        super(millisInFuture, countDownInterval);
        this.btn = button;
        this.msg = msg;
    }
    //计时过程中触发
    @Override
    public void onTick(long millisUntilFinished) {
        btn.setEnabled(false);
        btn.setText(millisUntilFinished / 1000 + "s");
    }
    //计时完成以后触发
    @Override
    public void onFinish() {
        btn.setEnabled(true);
        btn.setText(msg);
    }

}

界面上显示

public class MainActivity extends Activity {
    private Button btn;
    private MyCountDownTimer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        timer = new MyCountDownTimer(60 * 1000, 1000, btn, getResources()
                .getString(R.string.message));
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                timer.start();
            }
        });
    }
}

这里写图片描述

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值