Set Date Format Of TextClock In A Widget Programatically

6.7k views Asked by At

I have to set a TextClock to show the time as well as the date in another TextClock. I want to be able to enable the user to change the format of the date. Eg. instead of dd MMMM yyyy they want: MMMM dd yyyy which will show January 01 2013.

I have set up a spinner and array to choose this in a config Activity but want to know how to change the TextClock format to as I've mentioned. I have tried views.set.... but have found nothing.

Surely there must be a way to change the format like I have in the xml file

android:format12Hour="dd MMMM yyyy"
android:format24Hour="dd MMMM yyyy"

in the java file..

3

There are 3 answers

2
Hadriel On

Yes there is a setFormat12Hour(CharSequence) Method and 24Hour for a TextClock instance. The char sequence is just like the one you mention.

3
DEzra On

Update: 31st Jan 2018: There is a easier way of setting 24hour form via call to setCharSequence shown in this stackoverflow questions accepted answer: Can't call setFormat24Hour of a TextClock in a Widget

Old alternative answer: As the widgets view are accessed programmatically via the RemoteViews android class and that class doesn't expose the set24hourformat method,you have to work around the issue by creating two XML layouts (one for each format you want to switch between) and then set the XML layout using RemoteViews constructor.

A bit of a pain, but only way with current SDK APIs.

Here's an example that you would put in onUpdate():

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
    RemoteViews views = null;
    int layoutID = 0;
    if (TwentyFourHourOn){
        layoutID = R.layout.widget_clock_with_24hour;
    } else {
        layoutID = R.layout.widget_clock_with_12hour;
    }

    // the layoutID that is passed in the constructor of the
    //   RemoteViews object is the layout that will be loaded
    //   when the widget is updated.
    views = new RemoteViews(context.getPackageName(), layoutID);

    for (int i = 0; i < appWidgetIds.length; i++) {
        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }
}
2
2cupsOfTech On

That's what you need to do:

remoteView.setCharSequence(R.id.widget_current_date, "setFormat12Hour", datePattern);