android倒数计时器,Android倒计时(分钟)

本文介绍了如何在Android中使用CountDownTimer实现倒计时功能。通过onTick方法更新剩余时间,并在计时结束时触发特定操作。示例代码详细展示了如何设置文本、颜色和点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文通过CountDownTimer来实现倒计时的功能,先上效果图

34f40c9ec3b2

效果图.gif

1.核心方法就是通过onTick方法来获取时间的改变

public void onTick(long millisUntilFinished) {

//计时过程显示

this.millisUntilFinished = millisUntilFinished;

button.setTextColor(Color.parseColor("#FFFFFF"));

button.setClickable(false);

button.setTextSize((float) 11.5);

DecimalFormat dec = new DecimalFormat("##.##");

button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");

}

以下是完整代码

import android.graphics.Color;

import android.os.CountDownTimer;

import android.widget.TextView;

import java.text.DecimalFormat;

public class PeterTimeCountRefresh extends CountDownTimer {

private TextView button;

private long millisUntilFinished;

public PeterTimeCountRefresh(long millisInFuture, long countDownInterval, final TextView button) {

super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔,要显示的按钮

this.button = button;

}

@Override

public void onTick(long millisUntilFinished) {//计时过程显示

this.millisUntilFinished = millisUntilFinished;

button.setTextColor(Color.parseColor("#FFFFFF"));

//button.setBackgroundResource(R.drawable.send_code_wait);

button.setClickable(false);

button.setTextSize((float) 11.5);

DecimalFormat dec = new DecimalFormat("##.##");

button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");

}

@Override

public void onFinish() {//计时完毕时触发

button.setText("刷新");

button.setTextColor(Color.parseColor("#FFFFFF"));

// button.setBackgroundResource(R.drawable.send_code);

button.setClickable(true);

}

}

2.使用

PeterTimeCountRefresh timer = new PeterTimeCountRefresh(600000, 1000, btnRefresh);

timer.start();

3.最后,在onDestroy中关掉计时器,防止内存泄漏

@Override

protected void onDestroy() {

super.onDestroy();

if (timer != null) {

timer.cancel();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值