前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android获取验证码倒计时实现代码

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

作者头像
砸漏
发布2020-11-05 10:11:45
7150
发布2020-11-05 10:11:45
举报
文章被收录于专栏:恩蓝脚本

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

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

xml代码:

代码语言:javascript
复制
<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="50dp"
   android:background="@color/white"
   android:orientation="horizontal"  

   <EditText
     android:id="@+id/phonetext"
     android:layout_width="0dp"
     android:layout_height="match_parent"
     android:layout_weight="1"
     android:layout_marginLeft="15dp"
     android:layout_gravity="center_vertical"
     android:inputType="number"
     android:hint="请输入短信验证码"
     android:background="@null"/ 

   <Button
     android:id="@+id/timebutton"
     android:layout_width="wrap_content"
     android:layout_height="30dp"
     android:layout_marginRight="15dp"
     android:layout_marginTop="10dp"
     android:textSize="16dp"
     android:background="@drawable/tv_timemessage_bg"
     android:text="获取"
    / 
</LinearLayout 

效果如下:

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

JAVA代码:

代码语言:javascript
复制
/**
 * 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. 倒计时函数

代码语言:javascript
复制
//倒计时函数
  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. 清除倒计时函数,解决验证码输入正确后停止计时

代码语言:javascript
复制
private void clearTimer() {
    if (task != null) {
      task.cancel();
      task = null;
    }
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档