我在程序中使用定時器,我需要顯示將來幾天剩余的小時,分鐘和秒。
我獲取了時間,分鐘和秒,但是當我在text view上設置時,計時器不啟動。
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;
}
輸出:
為什麼計時器沒有開始?
可以試下下邊的方法
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
tv3.post(new Runnable() {
@Override
public void run() {
txt3.setText(timeCalculate(millisUntilFinished/1000) + " Countdown");
}
});
}