有一个时钟我想在一个TextView来显示。
have a clock I want to display in a TextView.
我还以为有几个不错的功能,要做到这一点,但我无法找到任何东西。 我最终实现了使用处理程序我自己的路。我要问,虽然,有没有更好的(更有效)的方式来显示实时更新时钟?
I would have thought there was a few nice functions to do this, but I couldn't find anything. I ended up implementing my own way that uses a Handler. What I'm asking though, is there a better (more efficient) way to display a real time updating clock?
private Runnable mUpdateClockTask = new Runnable() {
public void run() {
setTime();
mClockHandler.postDelayed(this, 1000);
}
};
这是我的处理程序,它运行的每一秒,然后我设定的时间和日期的功能是低于
That's my handler, which runs every second, and then my set time and date function is below
TextView mClockView;
public void setTime() {
Calendar cal = Calendar.getInstance();
int minutes = cal.get(Calendar.MINUTE);
if (DateFormat.is24HourFormat(this)) {
int hours = cal.get(Calendar.HOUR_OF_DAY);
mClockView.setText((hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes));
}
else {
int hours = cal.get(Calendar.HOUR);
mClockView.setText(hours + ":" + (minutes < 10 ? "0" + minutes : minutes) + " " + new DateFormatSymbols().getAmPmStrings()[cal.get(Calendar.AM_PM)]);
}
}
干杯
记住:premature的优化是一切罪恶的根源。因此,只有当你确信(=测量了它),你的代码是慢优化/低效率的。
Remember: premature optimization is the root of all evil. So only optimize when you are sure (=have measured it) that your implementation is slow/inefficient.
这是说,一个更有效的方法很可能是记录通过 System.currentTimeMillis的开始时间()
,然后定期检查和计算以分钟的差异。
That said, a more efficient method would probably be to record start time via System.currentTimeMillis()
and then periodically check it and calculate difference in minutes.