Skip to content

Instantly share code, notes, and snippets.

@ceosilvajr
Forked from derekstavis/DigitalClock.java
Last active August 29, 2015 14:25
Show Gist options
  • Save ceosilvajr/4059f7cfec06685a3afb to your computer and use it in GitHub Desktop.
Save ceosilvajr/4059f7cfec06685a3afb to your computer and use it in GitHub Desktop.
DigitalClock HH:MM for Android
package com.derekstavis;
public class DigitalClock extends TextView {
private int hours;
private int minutes;
private int seconds;
private Timer clockTimer;
private final TimerTask clockTask = new TimerTask() {
@Override
public void run() {
mHandler.post(mUpdateResults);
}
};
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
update();
}
};
public DigitalClock(Context context) {
super(context);
init();
}
private void update() {
seconds++;
if (seconds >= 60) {
seconds = 0;
if (minutes < 59) {
minutes++;
} else if (hours < 23) {
minutes = 0;
hours++;
} else {
minutes = 0;
hours = 0;
}
}
if (seconds % 2 == 0) {
setText(String.format("%02d:%02d", hours, minutes));
} else {
setText(String.format("%02d %02d", hours, minutes));
}
}
private void init() {
clockTimer = new Timer();
Calendar mCalendar = Calendar.getInstance();
hours = mCalendar.get(Calendar.HOUR_OF_DAY);
minutes = mCalendar.get(Calendar.MINUTE);
seconds = mCalendar.get(Calendar.SECOND);
clockTimer.scheduleAtFixedRate(clockTask, 0, 1000);
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DigitalClock(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
}
<com.derekstavis.DigitalClock
android:id="@+id/digitalClock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="120dp"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment