Android:如何在 TextView 中显示更新时钟

发布于 2024-12-03 15:57:25 字数 946 浏览 1 评论 0原文

我想在 TextView 中显示一个时钟。

我本以为有一些不错的功能可以做到这一点,但我找不到任何东西。 我最终实现了我自己的使用处理程序的方式。但我要问的是,是否有更好(更有效)的方法来显示实时更新时钟?

private Runnable mUpdateClockTask = new Runnable() {
   public void run() {
       setTime();
       mClockHandler.postDelayed(this, 1000);
   }
};

这是我的处理程序,每秒运行一次,然后我的设置时间和日期函数低于

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)]);
    }
}

干杯

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)]);
    }
}

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小嗲 2024-12-10 15:57:25

更新系统时钟与更新天文钟不同。我们讨论每分钟更改的时间(系统时钟分和00秒)。

使用计时器不是执行此操作的正确方法。这不仅是大材小用,而且还必须采取一些技巧来纠正。

执行此操作的正确方法(即更新显示时间为 HH:mm 的 TextView)是像这样使用 BroadcastReceiver :

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

系统将根据系统时钟在每分钟的确切开始发送此广播事件。但是,不要忘记提前初始化 TextView(到当前系统时间),因为您可能会在一分钟中间弹出 UI,并且 TextView 直到下一分钟才会更新。

Updating the system clock is not like updating a chronometer. We talk about the time changed on the minute (system clock minute and 00 seconds).

Using a Timer is not the right way to do this. It's not only overkill, but you must resort to some tricks to make it right.

The right way to do this (ie. update a TextView showing the time as HH:mm) is to use BroadcastReceiver like this :

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

The system will send this broadcast event at the exact beginning of every minutes based on system clock. Don't forget however to initialize your TextView beforehand (to current system time) since it is likely you will pop your UI in the middle of a minute and the TextView won't be updated until the next minute happens.

谁人与我共长歌 2024-12-10 15:57:25

查看 ChronometerDigitalClock类,它们是TextView类的扩展。他们应该自动执行您正在寻找的操作。如果您需要一些附加功能,只需查看这些功能的源代码并进行所需的任何更改。

更新:

由于 API 17 中不推荐使用数字时钟,因此我建议使用 文本时钟 代替。

Check out the Chronometer and DigitalClock classes, which are extensions of the TextView class. They should automatically do what you're looking for. If you need some additional functionality, just take a look at the source code for those and make any changes you need.

UPDATE:

Since digital clock is deprecated in API 17, I would recommend to use Text Clock instead.

等风也等你 2024-12-10 15:57:25

我推荐 TextClock (来自 API 17),也请不要使用 DigitalClock (从 API 17 开始弃用),因为它会导致内存泄漏并导致内存不足异常。
请将以下代码添加到相应的layout.xml文件中

 <TextClock
   android:id="@+id/textClock1"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:gravity="center_horizontal"
   android:textColor="#17d409" />

这将解决问题,另请注意,您可以根据需要格式化显示时间,例如要获得带秒的12小时格式,您可以使用“android:format12Hour=” hh:mm:ss 一个“”。

I recommend TextClock (From API 17), also please dont use DigitalClock (Deprecated from API 17) as it will cause MEMORY LEAK and will lead to Out of Memory Exception.
Please add the following piece of code to corresponding layout.xml file

 <TextClock
   android:id="@+id/textClock1"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:gravity="center_horizontal"
   android:textColor="#17d409" />

This will do the trick, also please note that you can format the displaying time as required for example for getting in 12 hour format with seconds you can use "android:format12Hour="hh:mm:ss a"".

小梨窩很甜 2024-12-10 15:57:25

您可以使用 android 提供的 TextClock 小部件

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="20sp"
    android:textStyle="bold" />

,它需要最低 API 级别 17

https://developer. android.com/reference/android/widget/TextClock

如果您希望在另一个文本视图中显示当前时间,

您可以使用下面的代码片段

 tClock = (TextClock) findViewById(R.id.textClock1);
        tView = (TextView) findViewById(R.id.textview1);
        btn = (Button)findViewById(R.id.btnGet);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tView.setText("Time: "+tClock.getText());
            }
        });
    }

You can use TextClock widget provided by android

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="20sp"
    android:textStyle="bold" />

it requires minimum API level 17

https://developer.android.com/reference/android/widget/TextClock

if you want the current time in another text view

you can use the below code snippet

 tClock = (TextClock) findViewById(R.id.textClock1);
        tView = (TextView) findViewById(R.id.textview1);
        btn = (Button)findViewById(R.id.btnGet);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tView.setText("Time: "+tClock.getText());
            }
        });
    }
偏闹i 2024-12-10 15:57:25

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

也就是说,更有效的方法可能是通过 System.currentTimeMillis() 记录开始时间,然后定期检查并计算以分钟为单位的差异。

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.

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.

若水般的淡然安静女子 2024-12-10 15:57:25

DigitalClock 小部件可在 android api 1 中使用,或者在 api 17 中使用 TextClock 小部件

创建时钟布局,如下所示:

<LinearLayout 
         android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/clocktext"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:layout_marginTop="30dp"
        android:textSize="50sp"
        android:text="2:46"/>
    <DigitalClock android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/clock"
        android:textStyle="bold"
        android:textSize="50sp"
        android:visibility="gone"
        android:textColor="#ffffff"
        />  
    </LinearLayout>       

在 Activity 中将 textchage 侦听器添加到 DigitalClock(它是 textview 的子类),因此我们可以添加 textchangedkistener 来获取更新的时间并设置时间根据需要添加到您的文本视图

chagre = (TextView) mTopView.findViewById(R.id.clocktext);// TextView to display Time
    clock = (DigitalClock) mTopView.findViewById(R.id.clock);// DigitalClock With visibility=gone

    clock.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {}

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {}
        @Override
        public void afterTextChanged(Editable s) {

            chagre.setText(s.toString());//will be called when system clock updataes

        }
    });

DigitalClock widget is available in android api 1 or use TextClock widget in api 17

create layout for clock like this first:

<LinearLayout 
         android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/clocktext"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:layout_marginTop="30dp"
        android:textSize="50sp"
        android:text="2:46"/>
    <DigitalClock android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/clock"
        android:textStyle="bold"
        android:textSize="50sp"
        android:visibility="gone"
        android:textColor="#ffffff"
        />  
    </LinearLayout>       

in Activity add textchage listener to the DigitalClock its a subclass of textview thus we can add textchangedkistener to get the updated time and set the time to your textview as you want

chagre = (TextView) mTopView.findViewById(R.id.clocktext);// TextView to display Time
    clock = (DigitalClock) mTopView.findViewById(R.id.clock);// DigitalClock With visibility=gone

    clock.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {}

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {}
        @Override
        public void afterTextChanged(Editable s) {

            chagre.setText(s.toString());//will be called when system clock updataes

        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文