Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing current time in Android and updating it?

I want to display current time and keep it updating, in this format example: 09:41 Hour:Minute. Is it possible to do in TextView? I tried some ways but I'm not getting what I actually want.

like image 677
Ajinkya More Avatar asked Apr 29 '15 19:04

Ajinkya More


2 Answers

Something like this should do the trick

final Handler someHandler = new Handler(getMainLooper());   
        someHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
                someHandler.postDelayed(this, 1000);
            }
        }, 10);

You should keep a reference to the handler and the runnable to cancel this when the Activity goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null in onDestroy

like image 131
Bojan Kseneman Avatar answered Nov 15 '22 19:11

Bojan Kseneman


Android has a view for this already.

http://developer.android.com/reference/android/widget/TextClock.html

You can use it directly in XML like so

<TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

It is min api 17, so you if need to go lower than that just look into

http://developer.android.com/reference/android/widget/DigitalClock.html

Worst case scenario you can subclass textview and steal the code from the textclock source. it should be fairly straightforward

like image 23
dabluck Avatar answered Nov 15 '22 18:11

dabluck