LocaleHelper.java revision ac5fe7c617c66850fff75a9fce9979c6e5674b0f
1/* 2 * Copyright (C) 2017 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 17package androidx.core.os; 18 19import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; 20 21import androidx.annotation.RestrictTo; 22 23import java.util.Locale; 24 25/** 26 * Helper to deal with new {@link Locale} APIs. 27 * 28 * @hide 29 */ 30@RestrictTo(LIBRARY_GROUP) 31final class LocaleHelper { 32 33 // Simpleton implementation for Locale.forLanguageTag(...) 34 static Locale forLanguageTag(String str) { 35 if (str.contains("-")) { 36 String[] args = str.split("-"); 37 if (args.length > 2) { 38 return new Locale(args[0], args[1], args[2]); 39 } else if (args.length > 1) { 40 return new Locale(args[0], args[1]); 41 } else if (args.length == 1) { 42 return new Locale(args[0]); 43 } 44 } else if (str.contains("_")) { 45 String[] args = str.split("_"); 46 if (args.length > 2) { 47 return new Locale(args[0], args[1], args[2]); 48 } else if (args.length > 1) { 49 return new Locale(args[0], args[1]); 50 } else if (args.length == 1) { 51 return new Locale(args[0]); 52 } 53 } else { 54 return new Locale(str); 55 } 56 57 throw new IllegalArgumentException("Can not parse language tag: [" + str + "]"); 58 } 59 60 // Simpleton implementation for Locale.toLanguageTag(...) 61 static String toLanguageTag(Locale locale) { 62 StringBuilder buf = new StringBuilder(); 63 buf.append(locale.getLanguage()); 64 final String country = locale.getCountry(); 65 if (country != null && !country.isEmpty()) { 66 buf.append("-"); 67 buf.append(locale.getCountry()); 68 } 69 70 return buf.toString(); 71 } 72} 73