Android的:在一个TextView如何显示的更新时钟 [英] Android: How do I display an updating clock in a TextView

查看:435
本文介绍了Android的:在一个TextView如何显示的更新时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个时钟我想在一个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.

这篇关于Android的:在一个TextView如何显示的更新时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆