发布于 

实现自定义倒计时View

更优雅的让TextView实时显示预设倒计时场景

背景

  • 项目后台接口已写好,而客户端发送验证码UI逻辑上需要实现类似于倒计时功能

实现

初步
1
2
3
4
5
6
7
8
9
while (time > 0) {
time--
print("还剩"+ time + "秒")
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
深入
通过Runnable实现
1
implements Runnable
定义其运行标识以及设定时间
1
2
private boolean isRun;
private int time=60;
开启及停止
1
2
3
4
5
6
7
8
public void start() {
this.isRun = true;
run();
}

public void stop() {
this.isRun = false;
}
自减值
1
2
3
4
5
6
7
8
private void count() {
time--;
if (time == 0) {
stop();
this.setText("请重试");
time=60;
}
}
run方法
1
2
3
4
5
6
7
8
9
10
@Override
public void run() {
count();
if (isRun) {
this.setText("还剩"+time+"秒");
postDelayed(this, 1000);
} else {
removeCallbacks(this);
}
}
调用
1
tv_fragment_business_settlement_send_verification_code.start()

理解

  • 通过标识真假判断是否执行 若执行便自减至0止步 其变化的数量实时显示在自定义控件上 适用于发送验证码功能模块开发