Home | History | Annotate | Download | only in format
      1 /*
      2  * Copyright (C) 2013 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.text.format;
     18 
     19 import java.util.Calendar;
     20 import java.util.UnknownFormatConversionException;
     21 import java.util.regex.Pattern;
     22 
     23 import com.android.ide.common.rendering.api.LayoutLog;
     24 import com.android.layoutlib.bridge.Bridge;
     25 import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
     26 
     27 /**
     28  * Delegate used to provide new implementation for native methods of {@link Time}
     29  *
     30  * Through the layoutlib_create tool, some native methods of Time have been replaced by calls to
     31  * methods of the same name in this delegate class.
     32  */
     33 public class Time_Delegate {
     34 
     35     // Regex to match odd number of '%'.
     36     private static final Pattern p = Pattern.compile("(?<!%)(%%)*%(?!%)");
     37 
     38     @LayoutlibDelegate
     39     /*package*/ static String format1(Time thisTime, String format) {
     40 
     41         try {
     42             // Change the format by adding changing '%' to "%1$t". This is required to tell the
     43             // formatter which argument to use from the argument list. '%%' is left as is. In the
     44             // replacement string, $0 refers to matched pattern. \\1 means '1', written this way to
     45             // separate it from 0. \\$ means '$', written this way to suppress the special meaning
     46             // of $.
     47             return String.format(
     48                     p.matcher(format).replaceAll("$0\\1\\$t"),
     49                     timeToCalendar(thisTime, Calendar.getInstance()));
     50         } catch (UnknownFormatConversionException e) {
     51             Bridge.getLog().fidelityWarning(LayoutLog.TAG_STRFTIME, "Unrecognized format", e, format);
     52             return format;
     53         }
     54     }
     55 
     56     private static Calendar timeToCalendar(Time time, Calendar calendar) {
     57         calendar.set(time.year, time.month, time.monthDay, time.hour, time.minute, time.second);
     58         return calendar;
     59     }
     60 
     61 }
     62