Android中验证码倒计时的简单实现方法示例
前言
现在的很多app都是使用手机注册的,为了确认使用的是自己的手机,都会加上一个短线验证码的选项,最近公司的项目使用到了这个短信验证码,并且要加入验证码倒计时功能,也就是60秒才能发送一次验证码,再次做过记录,以后使用的时候,可以随时拿来用。
实现
发送验证码的时候一般都会有一个按钮,点击之后便会给你输入的手机发送一条验证码,我这里使用的是一个TextView,显示特定的数字,只用设置TextView的点击事件即可;
Android中有一个类,可以很方便的时候该功能,但是也会存在一个问题,就是在最后一秒的时候,会等待很久才会显示出“重新发送”的文字,这个类是CountDownTimer,有兴趣的朋友可以去研究下,用起来还是挺方便的,不过我后来发现重新开启一个线程来实现是比较完美的。
代码如下:
/**
*短信验证码倒计时
*/
privatevoidstartTimer(){
registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_color_code_green));
registerVerificationCodeTv.setText(getResources().getString(R.string.timer_default_show));
registerVerificationCodeTv.setEnabled(false);
newThread(){
@Override
publicvoidrun(){
for(inti=59;i>=0;i--){
finalintsecond=i;
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
if(second<=0){
registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_get_verification_code));
registerVerificationCodeTv.setText(getResources().getString(R.string.register_re_get_verification_code));
registerVerificationCodeTv.setEnabled(true);
}else{
registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_color_code_green));
registerVerificationCodeTv.setText(second+"s");
}
}
});
}
}
}.start();
}
说明:
registerVerificationCodeTv就是那个显示倒计时秒数的TextView,用的时候只用在registerVerificationCodeTv的点击事件里面调用此方法就好了。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对毛票票的支持。