Last active
September 7, 2024 04:27
-
-
Save stdStudent/db91a8f7774ca6104636ebf27415084c to your computer and use it in GitHub Desktop.
Android, Locale utilities: get a currently displayed locale at a device's system level, validate a locale or a language tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Licensed under the BSD-3-Clause-Clear license. | |
* The license text in enclosed in the comment section. | |
*/ | |
/** | |
* The idea is to use the hidden SYSTEM_LOCALES ("system_locales") setting | |
* to get the currently displayed locale. Although the documentation says | |
* that one must use `LocaleList.getDefault` instead, I couldn't really | |
* get the right locale when I changed it in the system settings. | |
*/ | |
/** | |
* @return currently displayed locale at a device's system level or null | |
*/ | |
fun getCurrentLocale(context: Context): Locale? { | |
val devicesLocales = Settings.System.getString( | |
context.contentResolver, | |
"system_locales" | |
) | |
val displayedLocale = if (devicesLocales != null && devicesLocales.isNotEmpty()) { | |
// get the first language as it is what is currently displayed for the user | |
val locales = devicesLocales.split(",") | |
val languageTag = locales[0] | |
// retrieve locale from the language tag | |
Locale.forLanguageTag(languageTag) | |
} else { | |
// it should be unreachable, but you never know | |
null | |
} | |
return displayedLocale | |
} | |
/** | |
* @param fallbackLocale must be set in case the device's locale is not retrievable | |
* @return currently displayed locale at a device's system level or `fallbackLocale` | |
*/ | |
fun getCurrentLocale(context: Context, fallbackLocale: Locale): Locale { | |
return getCurrentLocale(context) ?: fallbackLocale | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Licensed under the BSD-3-Clause-Clear license. | |
* The license text in enclosed in the comment section. | |
*/ | |
fun isLocaleValid(locale: Locale): Boolean { | |
val availableLocales = Locale.getAvailableLocales() | |
return locale in availableLocales | |
} | |
fun isLanguageTagValid(languageTag: String): Boolean { | |
val availableLanguageTags = Locale.getAvailableLocales().map { it.toLanguageTag() } | |
return languageTag in availableLanguageTags | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LICENSE