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

查看:44
本文介绍了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)]);
    }
}

干杯

推荐答案

记住:过早的优化是万恶之源.因此,只有在您确定(=已经测量过)您的实施缓慢/低效时才进行优化.

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天全站免登陆