android 中有一个封装好的CountDownTimer类,可以直接调用实现倒计时效果。
代码实现:
新建一个TimerCount类:
public class TimerCount extends CountDownTimer {
private Button bnt;
//第一个参数代表总时长,第二个代表间隔时间,第三个是自己添加的参数,调用的时候传入需要的参数时使用
public TimerCount(long millisInFuture, long countDownInterval, Button bnt) {
super(millisInFuture, countDownInterval);
this.bnt = bnt;
}
public TimerCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
//倒计时结束后的处理,这里让button不可用且显示相应字符
@Override
public void onFinish() {
bnt.setEnabled(true);
bnt.setText("获取验证码");
}
//倒计时过程中的设置
@SuppressLint("ResourceAsColor")
@Override
public void onTick(long arg0) {
// 设置倒计时过程中的字体属性
bnt.setTextColor(R.color.divider);
bnt.setText(arg0 / 1000 + "");
bnt.setEnabled(false);
}
}其他类对其调用:
@OnClick(R.id.get_code)
<span style="white-space:pre"> </span>void Code() {
<span style="white-space:pre"> </span><span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);">TimerCount timerCount = new TimerCount(60000, 1000, get_code);timerCount.start();</span>
<span style="white-space:pre"> </span>}
本文介绍了在Android中如何使用CountDownTimer类实现点击获取验证码后的倒计时功能,确保按钮在计时期间处于不可用状态。

1566

被折叠的 条评论
为什么被折叠?



