Android获取验证码倒计时

获取验证码倒计时,切换页面或finish后,计时持续不间断的简易使用方法:

public class Example extends Activity{

    private Button getCode_btn;//获取验证码按钮
    public static CountDownTimer getCode_CDtimer;// 获取验证码计时器
    public static long timeRemain;// 时间剩余记录


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example);//布局文件自己自定义
        getCode_btn = (Button) findViewById(R.id.getCode_btn);
        if (Example .getCode_CDtimer != null) {// 如果获取验证码的计时器正在计时
            Example .getCode_CDtimer.cancel();// 则获取当前剩余时间
            timeRemain(Example .timeRemain);// 重新已剩余时间为基础计时
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.getCode_btn:// 获取验证码按钮被点击
                getCode_btn.setEnabled(false);// 按钮不可点击
                timeRemain(60l);// 时间设置60秒计时
                break;
    }

    /**
     * 
     * @param 时间
     *  获取验证码时间计时器初始化
     */

    public void timeRemain(Long arg0) {

        Example .getCode_CDtimer = new CountDownTimer(arg0 * 1000,
                1000) {

            @Override
            public void onTick(long arg0) {
                getCode_btn.setText(arg0 / 1000 + "秒");// 每隔1秒显示时间剩余
                Example .timeRemain = arg0 / 1000;// 保存剩余时间
                // Log.v("timer", Example .timeRemain +"");
                if (arg0 <= 0) {
                    Example .timeRemain = 60l;// 计时完成剩余时间记录重置60s
                }
            }

            @Override
            public void onFinish() {
                getCode_btn.setText("获取验证码");
                getCode_btn.setEnabled(true);// 60秒结束后按钮可点击

            }
        }.start();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值