在app中经常会出现短信验证码的情况,而短信验证码有个功能,就是显示一个倒计时,60秒后重新发送。
在android中有个控件,叫做CountDownTimer,就是实现这种倒计时功能的,下面是CountDownTimer的用法,给一个布局增加一个点击事件,并在点击事件里面写上以下代码:
new CountDownTimer(60000, 1000) {
@SuppressLint("ResourceAsColor")
public void onTick(long millisUntilFinished) {
activity_load_forget_ll1.setBackgroundResource(R.color.line);
activity_load_forget_tv1.setText( "重新获取"+"("+millisUntilFinished / 1000 +"s"+")");
activity_load_forget_tv1.setTextColor(Color.parseColor("#000000"));
activity_load_forget_tv1.setEnabled(false);
}
@SuppressLint("ResourceAsColor")
public void onFinish() {
activity_load_forget_ll1.setBackgroundResource(R.color.mine);
activity_load_forget_tv1.setTextColor(Color.parseColor("#ffffff"));
activity_load_forget_tv1.setText("获取验证码");
activity_load_forget_tv1.setEnabled(true);
}
}.start();
60000代表60000毫秒也就是倒计时60秒,1000代表每次跳动1000毫秒也就是1秒,之后就是个布局设置点击之后呈现出来的背景色,文本内容,文本颜色等, setEnabled(false)是让布局不可点击,60秒走完之后就执行onFinish函数,重新设置背景色,文本以及文本颜色,并将布局设置为可点击,最后记得加上start(),这样就实现了一个倒计时60秒的功能。