最近遇到了需要隐藏状态栏,但又要显示时间的问题。 找了一下,原来有现成的组件(DigitalClock)可以用来显示时间,所以就在全屏后的界面添加了一个DigitalClock。效果可以显示,不过跟系统的状态栏时间相比,多了一个秒钟时时再跳,感觉总是那么不舒服。
所以想办法,看了一下源码发现,原来修改一下代码即可。
1、 修改后自定义DigitalClock的代码如下:
public class DigitalClock extends android.widget.DigitalClock {
Calendar mCalendar;
private final static String m12 = "h:mm";// 修改部分,原来为 h:mm:ss aa
private final static String m24 = "k:mm";// 修改部分,原来为 k:mm:ss
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
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 = context.getResources();
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
@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;
}
/**
* Pulls 12/24 mode from system settings
*/
private boolean get24HourMode() {
return android.text.format.DateFormat.is24HourFormat(getContext());
}
private void setFormat() {
if (get24HourMode()) {
mFormat = m24;
} else {
mFormat = m12;
}
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
setFormat();
}
}
}
2,调用时,直接在 layout 布局文件中添加即可,如下:
<com.test.view.DigitalClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="3dp"
android:textSize="16sp"
android:textColor="#ffffff" />