Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Yazan98/dbdd3c33e4601c9b307ac3c9de6c0efe to your computer and use it in GitHub Desktop.
Save Yazan98/dbdd3c33e4601c9b307ac3c9de6c0efe to your computer and use it in GitHub Desktop.
suspend fun changeApplicationLanguage(context: Context, newLanguage: String) {
withContext(Dispatchers.Main) {
val config = context.resources.configuration;
val sysLocale: Locale? = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
getSystemLocale(config)
} else {
getSystemLocaleLegacy(config)
}
sysLocale?.let {
if (!newLanguage.equals("") && !it.language.equals(newLanguage)) {
val locale = Locale(newLanguage);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
}
context.createConfigurationContext(config)
}
}
}
private fun getSystemLocaleLegacy(config: Configuration): Locale? {
return config.locale
}
@TargetApi(Build.VERSION_CODES.N)
fun getSystemLocale(config: Configuration): Locale? {
return config.locales[0]
}
private fun setSystemLocaleLegacy(config: Configuration, locale: Locale?) {
config.locale = locale
}
@TargetApi(Build.VERSION_CODES.N)
fun setSystemLocale(config: Configuration, locale: Locale?) {
config.setLocale(locale)
}
suspend fun attachBaseContext(context: Context, defLanguage: String) {
withContext(Dispatchers.Main) {
changeApplicationLanguage(context, defLanguage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment