Skip to content

Commit

Permalink
Move constructing a Locale from an Android format string to a method
Browse files Browse the repository at this point in the history
  • Loading branch information
simonpoole committed Nov 20, 2023
1 parent 1e5096e commit 6d41ad3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
Expand Up @@ -119,8 +119,7 @@ private void setupAppLocalePref(@NonNull ListPreference appLocalePref) {
// Note google is very confused about Android with _ and proper, with - locale values, we try to circumvent
// that here
if (Util.notEmpty((String) newValue)) {
String[] code = ((String) newValue).split("_");
Locale newLocale = code.length == 1 ? new Locale(code[0]) : new Locale(code[0], code[1]);
Locale newLocale = LocaleUtils.localeFromAndroidLocaleTag((String) newValue);
LocaleListCompat newAppList = LocaleListCompat.create(newLocale);
AppCompatDelegate.setApplicationLocales(newAppList);
preference.setSummary(newLocale.getDisplayName());
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/de/blau/android/util/LocaleUtils.java
Expand Up @@ -23,6 +23,8 @@ public final class LocaleUtils {

private static final String DEBUG_TAG = LocaleUtils.class.getSimpleName();

private static final String ANDROID_LOCALE_SEPARATOR = "_";

// list of languages that use Latin script from https://gist.github.com/phil-brown/8056700
private static Set<String> latin = new HashSet<>(Arrays.asList("aa", "ace", "ach", "ada", "af", "agq", "ak", "ale", "amo", "an", "arn", "arp", "arw", "asa",
"ast", "ay", "az", "bal", "ban", "bas", "bbc", "bem", "bez", "bi", "bik", "bin", "bku", "bla", "bm", "bqv", "br", "bs", "buc", "bug", "bya", "ca",
Expand Down Expand Up @@ -212,4 +214,16 @@ public static LocaleListCompat getSupportedLocales(@NonNull Context context) {
}
return LocaleListCompat.forLanguageTags(String.join(",", locales));
}

/**
* Construct a Locale from an Android format locale string
*
* @param localeString the Android format locale string
* @return a Locale
*/
@NonNull
public static Locale localeFromAndroidLocaleTag(@NonNull String localeString) {
String[] code = localeString.split(ANDROID_LOCALE_SEPARATOR);
return code.length == 1 ? new Locale(code[0]) : new Locale(code[0], code[1]);
}
}

0 comments on commit 6d41ad3

Please sign in to comment.