您的位置:首页 > 移动开发 > Android开发

Android 倒计时

2016-05-23 00:00 471 查看
摘要: 倒计时

法一:

方法一 : public class Counter extends CountDownTimer {
private static final int SECONDS = 60; // 秒数
private static final int MINUTES = 60 * 60; // 小时

private long first = 0, twice = 0, third = 0;
private long mtmp = 0, mtmp2 = 0;

public Counter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}

@Override
public void onFinish() {
// TODO Auto-generated method stub

}

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
// 获取当前时间总秒数
first = millisUntilFinished / 1000;
if (first < SECONDS) { // 小于一分钟 只显示秒
tvSetTime
.setText("00:00:" + (first < 10 ? "0" + first : first));
} else if (first < MINUTES) { // 大于或等于一分钟,但小于一小时,显示分钟
twice = first % 60; // 将秒转为分钟取余,余数为秒
mtmp = first / 60; // 将秒数转为分钟
if (twice == 0) {
tvSetTime.setText("00:" + (mtmp < 10 ? "0" + mtmp : mtmp)
+ ":00"); // 只显示分钟
} else {
tvSetTime.setText("00:" + (mtmp < 10 ? "0" + mtmp : mtmp)
+ ":" + (twice < 10 ? "0" + twice : twice)); // 显示分钟和秒
}
} else {
twice = first % 3600; // twice为余数 如果为0则小时为整数
mtmp = first / 3600;
if (twice == 0) {
// 只剩下小时
tvSetTime.setText("0" + first / 3600 + ":00:00");
} else {
if (twice < SECONDS) { // twice小于60 为秒
tvSetTime.setText((mtmp < 10 ? "0" + mtmp : mtmp)
+ ":00:" + (twice < 10 ? "0" + twice : twice)); // 显示小时和秒
} else {
third = twice % 60; // third为0则剩下分钟 否则还有秒
mtmp2 = twice / 60;
if (third == 0) {
tvSetTime.setText((mtmp < 10 ? "0" + mtmp : mtmp)
+ ":" + (mtmp2 < 10 ? "0" + mtmp2 : mtmp2)
+ ":00");
} else {
tvSetTime.setText((mtmp < 10 ? "0" + mtmp : mtmp)
+ ":" + (mtmp2 < 10 ? "0" + mtmp2 : mtmp2)
+ ":" + third); // 还有秒
}
}
}
}
}

}

法二:

public void StartTime(int i) {
time_num = i;
if (istime != null) {
istime.cancel();
istime = null;
}
istime = new Timer();
text_time.setText(time_num / 60 + ":" + time_num % 60);
istime.schedule(new TimerTask() {
@Override
public void run() {
// TODO 自动生成的方法存根
if (time_num > 0)
time_num--;
else {
istime.cancel();
istime = null;
}
han_time.sendMessage(new Message());
}
}, 1000, 1000);
}

public void StopTime() {
if (istime != null) {
istime.cancel();
istime = null;
}
}

Handler han_time = new Handler() {
public void handleMessage(Message msg) {
text_time.setText(String.format("%02d", time_num / 60) + ":"
+ String.format("%02d", time_num % 60));
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: