改编自您链接到的 DigitalClock 类。
package com.t3hh4xx0r.examplewidget
import android.content.Context;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import java.util.Calendar;
public class CustomDigitalClock extends TextView {
Calendar mCalendar;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat = "h:mm aa";
public DigitalClock(Context context) {
super(context);
initClock(context);
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock(context);
}
private void initClock(Context context) {
Resources r = mContext.getResources();
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
}
@Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
}