热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android获取验证码倒计时实现代码

这篇文章主要为大家详细介绍了Android获取验证码倒计时的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android获取验证码倒计时的具体代码,供大家参考,具体内容如下

1. 验证码输入框和获取验证码按钮布局

xml代码:



   

   

效果如下:

2. 根据id设置Button点击事件触发倒计时

JAVA代码:

/**
 * Created by fby on 2017/9/11.
 */
public class ChargepsdActivity extends Activity {

  private Button timeButton;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chargepsd);

    timeButton = (Button) findViewById(R.id.timebutton);
    //new倒计时对象,总共的时间,每隔多少秒更新一次时间
    final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000,1000);

    //设置Button点击事件触发倒计时
    timeButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        myCountDownTimer.start();
      }
    });
}

3. 倒计时函数

//倒计时函数
  private class MyCountDownTimer extends CountDownTimer {

    public MyCountDownTimer(long millisInFuture, long countDownInterval) {
      super(millisInFuture, countDownInterval);
    }

    //计时过程
    @Override
    public void onTick(long l) {
      //防止计时过程中重复点击
      timeButton.setClickable(false);
      timeButton.setText(l/1000+"秒");

    }

    //计时完毕的方法
    @Override
    public void onFinish() {
      //重新给Button设置文字
      timeButton.setText("重新获取");
      //设置可点击
      timeButton.setClickable(true);
    }
  }

}

4. 清除倒计时函数,解决验证码输入正确后停止计时

private void clearTimer() {
    if (task != null) {
      task.cancel();
      task = null;
    }
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
author-avatar
你是我的小二郎
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有