Android: How do I display an updating clock in a TextView

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"".


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.


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.