我在我的应用程序中使用倒数计时器,我需要以天数小时分钟和秒数显示即将到来的日期。我得到了天数、小时、分钟和秒,但是当我将其设置为 TextView 时,倒计时不会开始.以下是我的代码。
Date date = new Date(2013,Integer.parseInt(datess.get(k).split("-")[1])-1,Integer.parseInt(datess.get(k).split("-")[0]),hours,mins,secs);
long dtMili = System.currentTimeMillis();
Date dateNow = new Date(dtMili);
remain = date.getTime() - dateNow.getTime();
MyCount counter = new MyCount(remain,1000);
counter.start();
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
tv3.setText("done");
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
tv3.setText(timeCalculate(millisUntilFinished/1000) + " Countdown");
}
}
public String timeCalculate(long ttime)
{
long daysuuu,hoursuuu, minutesuuu, secondsuuu;
String daysT = "", restT = "";
daysuuu = (Math.round(ttime) / 86400);
hoursuuu = (Math.round(ttime) / 3600) - (daysuuu * 24);
minutesuuu = (Math.round(ttime) / 60) - (daysuuu * 1440) - (hoursuuu * 60);
secondsuuu = Math.round(ttime) % 60;
if(daysuuu==1) daysT = String.format("%d day ", daysuuu);
if(daysuuu>1) daysT = String.format("%d days ", daysuuu);
restT = String.format("%02d:%02d:%02d", hoursuuu, minutesuuu, secondsuuu);
return daysT + restT;
}
这是输出
为什么倒计时没有开始?任何建议表示赞赏。
Best Answer-推荐答案 strong>
您没有使用 millisUntilFinished 参数来更新您在 timeCalculate() 中的时间.开始:
@Override
public void onTick(long millisUntilFinished) {
tv3.setText(millisUntilFinished + " Countdown");
}
一旦您确认计时器正在工作,您将需要一个方法来转换 millisUntilFinished 变成人类可读的字符串。
Java 中与日期和时间相关的类不必要地难以使用并且有一些难以理解的错误。 (例如,大部分 Date 类已被弃用,但推荐的 Calendar 类仍然严重依赖 Date...) 3rd 方库 Joda Time是一种流行的替代品。
加法
the output is not what i expected
future 25,000 到 700 天也不是我所期望的,date 似乎是错误的。正如 gabriel 在 another answer 中指出的那样对于这个问题,年份值是从 1900 年开始计算的。虽然还有其他问题,因为 25,000 天距离 future 不到 70 年......
但是,此构造函数已弃用,不应使用,Calendar 是推荐的类。我写了一个 quick demo为您使用日历。
但请理解 CountDownTimer 本身有几个基本缺陷:
- 每次
onTick() 被称为 CDT 给整体时间增加了几毫秒,我注意到它每天可以轻松增加 7 分半钟。
- 由于第一个错误,最后一个
onTick() 可能不会被调用。从 5 开始倒计时,我通常会看到 "5, 4, 3, 2, <long pause>" 然后 onFinished() 显示 "0" ...
我在上一个问题中重写了 CDT:android CountDownTimer - additional milliseconds delay between ticks .
关于android - 在android中使用倒数计时器显示天时分秒时的倒计时问题,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/13833850/
|