FileDocCategorySizeDatePackage
TextClock.javaAPI DocAndroid 5.1 API19073Thu Mar 12 22:22:10 GMT 2015android.widget

TextClock

public class TextClock extends TextView

TextClock can display the current date and/or time as a formatted string.

This view honors the 24-hour format system setting. As such, it is possible and recommended to provide two different formatting patterns: one to display the date/time in 24-hour mode and one to display the date/time in 12-hour mode. Most callers will want to use the defaults, though, which will be appropriate for the user's locale.

It is possible to determine whether the system is currently in 24-hour mode by calling {@link #is24HourModeEnabled()}.

The rules used by this widget to decide how to format the date and time are the following:

  • In 24-hour mode:
    • Use the value returned by {@link #getFormat24Hour()} when non-null
    • Otherwise, use the value returned by {@link #getFormat12Hour()} when non-null
    • Otherwise, use a default value appropriate for the user's locale, such as {@code h:mm a}
  • In 12-hour mode:
    • Use the value returned by {@link #getFormat12Hour()} when non-null
    • Otherwise, use the value returned by {@link #getFormat24Hour()} when non-null
    • Otherwise, use a default value appropriate for the user's locale, such as {@code HH:mm}

The {@link CharSequence} instances used as formatting patterns when calling either {@link #setFormat24Hour(CharSequence)} or {@link #setFormat12Hour(CharSequence)} can contain styling information. To do so, use a {@link android.text.Spanned} object. Note that if you customize these strings, it is your responsibility to supply strings appropriate for formatting dates and/or times in the user's locale.

attr
ref android.R.styleable#TextClock_format12Hour
attr
ref android.R.styleable#TextClock_format24Hour
attr
ref android.R.styleable#TextClock_timeZone

Fields Summary
public static final CharSequence
DEFAULT_FORMAT_12_HOUR
The default formatting pattern in 12-hour mode. This pattern is used if {@link #setFormat12Hour(CharSequence)} is called with a null pattern or if no pattern was specified when creating an instance of this class. This default pattern shows only the time, hours and minutes, and an am/pm indicator.
public static final CharSequence
DEFAULT_FORMAT_24_HOUR
The default formatting pattern in 24-hour mode. This pattern is used if {@link #setFormat24Hour(CharSequence)} is called with a null pattern or if no pattern was specified when creating an instance of this class. This default pattern shows only the time, hours and minutes.
private CharSequence
mFormat12
private CharSequence
mFormat24
private CharSequence
mFormat
private boolean
mHasSeconds
private boolean
mAttached
private Calendar
mTime
private String
mTimeZone
private boolean
mShowCurrentUserTime
private final android.database.ContentObserver
mFormatChangeObserver
private final android.content.BroadcastReceiver
mIntentReceiver
private final Runnable
mTicker
Constructors Summary
public TextClock(android.content.Context context)
Creates a new clock using the default patterns for the current locale.

param
context The Context the view is running in, through which it can access the current theme, resources, etc.

        super(context);
        init();
    
public TextClock(android.content.Context context, android.util.AttributeSet attrs)
Creates a new clock inflated from XML. This object's properties are intialized from the attributes specified in XML. This constructor uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.

param
context The Context the view is running in, through which it can access the current theme, resources, etc.
param
attrs The attributes of the XML tag that is inflating the view

        this(context, attrs, 0);
    
public TextClock(android.content.Context context, android.util.AttributeSet attrs, int defStyleAttr)
Creates a new clock inflated from XML. This object's properties are intialized from the attributes specified in XML.

param
context The Context the view is running in, through which it can access the current theme, resources, etc.
param
attrs The attributes of the XML tag that is inflating the view
param
defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

        this(context, attrs, defStyleAttr, 0);
    
public TextClock(android.content.Context context, android.util.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();
    
Methods Summary
private static java.lang.CharSequenceabc(java.lang.CharSequence a, java.lang.CharSequence b, java.lang.CharSequence c)
Returns a if not null, else return b if not null, else return c.

        return a == null ? (b == null ? c : b) : a;
    
private voidchooseFormat()
Selects either one of {@link #getFormat12Hour()} or {@link #getFormat24Hour()} depending on whether the user has selected 24-hour format. Calling this method does not schedule or unschedule the time ticker.

        chooseFormat(true);
    
private voidchooseFormat(boolean handleTicker)
Selects either one of {@link #getFormat12Hour()} or {@link #getFormat24Hour()} depending on whether the user has selected 24-hour format.

param
handleTicker true if calling this method should schedule/unschedule the time ticker, false otherwise

        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();
        }
    
private voidcreateTime(java.lang.String timeZone)

        if (timeZone != null) {
            mTime = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
        } else {
            mTime = Calendar.getInstance();
        }
    
public java.lang.CharSequencegetFormat()
Returns the current format string. Always valid after constructor has finished, and will never be {@code null}.

hide

        return mFormat;
    
public java.lang.CharSequencegetFormat12Hour()
Returns the formatting pattern used to display the date and/or time in 12-hour mode. The formatting pattern syntax is described in {@link DateFormat}.

return
A {@link CharSequence} or null.
see
#setFormat12Hour(CharSequence)
see
#is24HourModeEnabled()

        return mFormat12;
    
public java.lang.CharSequencegetFormat24Hour()
Returns the formatting pattern used to display the date and/or time in 24-hour mode. The formatting pattern syntax is described in {@link DateFormat}.

return
A {@link CharSequence} or null.
see
#setFormat24Hour(CharSequence)
see
#is24HourModeEnabled()

        return mFormat24;
    
public java.lang.StringgetTimeZone()
Indicates which time zone is currently used by this view.

return
The ID of the current time zone or null if the default time zone, as set by the user, must be used
see
TimeZone
see
java.util.TimeZone#getAvailableIDs()
see
#setTimeZone(String)

        return mTimeZone;
    
private voidinit()

        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);
    
public booleanis24HourModeEnabled()
Indicates whether the system is currently using the 24-hour mode. When the system is in 24-hour mode, this view will use the pattern returned by {@link #getFormat24Hour()}. In 12-hour mode, the pattern returned by {@link #getFormat12Hour()} is used instead. If either one of the formats is null, the other format is used. If both formats are null, the default formats for the current locale are used.

return
true if time should be displayed in 24-hour format, false if it should be displayed in 12-hour format.
see
#setFormat12Hour(CharSequence)
see
#getFormat12Hour()
see
#setFormat24Hour(CharSequence)
see
#getFormat24Hour()

        if (mShowCurrentUserTime) {
            return DateFormat.is24HourFormat(getContext(), ActivityManager.getCurrentUser());
        } else {
            return DateFormat.is24HourFormat(getContext());
        }
    
protected voidonAttachedToWindow()

        super.onAttachedToWindow();

        if (!mAttached) {
            mAttached = true;

            registerReceiver();
            registerObserver();

            createTime(mTimeZone);

            if (mHasSeconds) {
                mTicker.run();
            } else {
                onTimeChanged();
            }
        }
    
protected voidonDetachedFromWindow()

        super.onDetachedFromWindow();

        if (mAttached) {
            unregisterReceiver();
            unregisterObserver();

            getHandler().removeCallbacks(mTicker);

            mAttached = false;
        }
    
private voidonTimeChanged()

        mTime.setTimeInMillis(System.currentTimeMillis());
        setText(DateFormat.format(mFormat, mTime));
    
private voidregisterObserver()

        final ContentResolver resolver = getContext().getContentResolver();
        if (mShowCurrentUserTime) {
            resolver.registerContentObserver(Settings.System.CONTENT_URI, true,
                    mFormatChangeObserver, UserHandle.USER_ALL);
        } else {
            resolver.registerContentObserver(Settings.System.CONTENT_URI, true,
                    mFormatChangeObserver);
        }
    
private voidregisterReceiver()

        final IntentFilter filter = new IntentFilter();

        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);

        getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
    
public voidsetFormat12Hour(java.lang.CharSequence format)

Specifies the formatting pattern used to display the date and/or time in 12-hour mode. The formatting pattern syntax is described in {@link DateFormat}.

If this pattern is set to null, {@link #getFormat24Hour()} will be used even in 12-hour mode. If both 24-hour and 12-hour formatting patterns are set to null, the default pattern for the current locale will be used instead.

Note: if styling is not needed, it is highly recommended you supply a format string generated by {@link DateFormat#getBestDateTimePattern(java.util.Locale, String)}. This method takes care of generating a format string adapted to the desired locale.

param
format A date/time formatting pattern as described in {@link DateFormat}
see
#getFormat12Hour()
see
#is24HourModeEnabled()
see
DateFormat#getBestDateTimePattern(java.util.Locale, String)
see
DateFormat
attr
ref android.R.styleable#TextClock_format12Hour

        mFormat12 = format;

        chooseFormat();
        onTimeChanged();
    
public voidsetFormat24Hour(java.lang.CharSequence format)

Specifies the formatting pattern used to display the date and/or time in 24-hour mode. The formatting pattern syntax is described in {@link DateFormat}.

If this pattern is set to null, {@link #getFormat24Hour()} will be used even in 12-hour mode. If both 24-hour and 12-hour formatting patterns are set to null, the default pattern for the current locale will be used instead.

Note: if styling is not needed, it is highly recommended you supply a format string generated by {@link DateFormat#getBestDateTimePattern(java.util.Locale, String)}. This method takes care of generating a format string adapted to the desired locale.

param
format A date/time formatting pattern as described in {@link DateFormat}
see
#getFormat24Hour()
see
#is24HourModeEnabled()
see
DateFormat#getBestDateTimePattern(java.util.Locale, String)
see
DateFormat
attr
ref android.R.styleable#TextClock_format24Hour

        mFormat24 = format;

        chooseFormat();
        onTimeChanged();
    
public voidsetShowCurrentUserTime(boolean showCurrentUserTime)
Sets whether this clock should always track the current user and not the user of the current process. This is used for single instance processes like the systemUI who need to display time for different users.

hide

        mShowCurrentUserTime = showCurrentUserTime;

        chooseFormat();
        onTimeChanged();
        unregisterObserver();
        registerObserver();
    
public voidsetTimeZone(java.lang.String timeZone)
Sets the specified time zone to use in this clock. When the time zone is set through this method, system time zone changes (when the user sets the time zone in settings for instance) will be ignored.

param
timeZone The desired time zone's ID as specified in {@link TimeZone} or null to user the time zone specified by the user (system time zone)
see
#getTimeZone()
see
java.util.TimeZone#getAvailableIDs()
see
TimeZone#getTimeZone(String)
attr
ref android.R.styleable#TextClock_timeZone

        mTimeZone = timeZone;

        createTime(timeZone);
        onTimeChanged();
    
private voidunregisterObserver()

        final ContentResolver resolver = getContext().getContentResolver();
        resolver.unregisterContentObserver(mFormatChangeObserver);
    
private voidunregisterReceiver()

        getContext().unregisterReceiver(mIntentReceiver);