今天在使用TextClock的时候,碰到一个问题:只给TextClock设置setFormat24Hour(),没有设置setFormat12Hour(),系统显示的格式是默认的格式,而不是我想要的setFormat24Hour格式。例如,代码如下:
textClock.setFormat24Hour("yyyy-MM-dd HH:mm");
分析原因,因为当前系统的格式是12小时制(调用函数is24HourModeEnabled()可以得到当前系统是否为24小时制),而代码制设置了24小时制,没有设置12小时制,所以,系统就用 了默认的12小时制。TextClock的文档中有一段说明时间格式的使用规则:
In 24-hour mode:
Use the value returned by getFormat24Hour() when non-null
Otherwise, use the value returned by getFormat12Hour() when non-null
Otherwise, use a default value appropriate for the user's locale, such as h:mm a
In 12-hour mode:
Use the value returned by getFormat12Hour() when non-null
Otherwise, use the value returned by getFormat24Hour() when non-null
Otherwise, use a default value appropriate for the user's locale, such as HH:mm
相关源码如下:
private void chooseFormat(boolean handleTicker) {
final boolean format24Requested = is24HourModeEnabled();
LocaleData ld = LocaleData.get(getContext().getResources().getConfiguration().locale);
if (format24Requested) {
mFormat = abc(mFormat24, mFormat12, ld.timeFormat24);
} else {
mFormat = abc(mFormat12, mFormat24, ld.timeFormat12);
}
boolean hadSeconds = mHasSeconds;
mHasSeconds = DateFormat.hasSeconds(mFormat);
if (handleTicker && mAttached && hadSeconds != mHasSeconds) {
if (hadSeconds) getHandler().removeCallbacks(mTicker);
else mTicker.run();
}
}
/**
* Returns a if not null, else return b if not null, else return c.
*/
private static CharSequence abc(CharSequence a, CharSequence b, CharSequence c) {
return a == null ? (b == null ? c : b) : a;
}
上面说明,在24小时制的时候,
如果 getFormat24Hour()不为空,则使用getFormat24Hour()设置的格式。否则,如果getFormat12Hour() 不为空,使用getFormat12Hour()设置的格式。
否则,使用默认的格式。
12小时制的时候,
如果getFormat12Hour() 不为空,使用getFormat12Hour()设置的格式。
否则,如果 getFormat24Hour()不为空,则使用getFormat24Hour()设置的格式。
否则,使用默认的格式。
但是,事实上,getFormat12Hour() 和getFormat24Hour()默认值的不为空的,看以下源码:
public TextClock(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.TextClock, defStyleAttr, defStyleRes);
try {
mFormat12 = a.getText(R.styleable.TextClock_format12Hour);
mFormat24 = a.getText(R.styleable.TextClock_format24Hour);
mTimeZone = a.getString(R.styleable.TextClock_timeZone);
} finally {
a.recycle();
}
init();
}
private void init() {
if (mFormat12 == null || mFormat24 == null) {
LocaleData ld = LocaleData.get(getContext().getResources().getConfiguration().locale);
if (mFormat12 == null) {
mFormat12 = ld.timeFormat12;
}
if (mFormat24 == null) {
mFormat24 = ld.timeFormat24;
}
}
createTime(mTimeZone);
// Wait until onAttachedToWindow() to handle the ticker
chooseFormat(false);
}
在构造函数中,就给mFormat12(getFormat12Hour()的返回值)和mFormat24 ( getFormat24Hour()的返回值 )都附了初始值。所以默认情况下,上面的规则只有第一条会执行。
结论:如果要设置实际的时间格式的话,两种方法:
1、setFormat24Hour()和setFormat12Hour()同时设置相同的格式
2、把setFormat24Hour()和setFormat12Hour()其中的一个设为空,另一个为你需要的格式。