I'm trying to support the Arabic language. When I changed the language in the application with the following code (refer below), in most of the devices it works fine but in some devices such as Galaxy S7, Galaxy S8, LG G5
UI transforms to RTL
successfully but Arabic language resources are not being loaded and the app still uses EN
string resources.
Has anyone had any opinions about this problem? Thanks for answers.
Here is the code I use for changing language:
private fun updateResources(context: Context, locale: Locale): Context {
Locale.setDefault(locale)
val res = context.resources
val config = res.configuration
config.setLocale(locale)
config.setLayoutDirection(locale)
BaseActivity.setLayoutDirection(res.configuration.layoutDirection)
Session.lang = locale.language
return context.createConfigurationContext(config)
}
In your activity, override attachBaseContext function
override fun attachBaseContext(base: Context) {
super.attachBaseContext(updateBaseContextLocale(base))
}
updateBaseContextLocale function is like below;
private fun updateBaseContextLocale(context: Context): Context {
val languageCode = LanguageUtils.getLanguageCode(LocalSharedPrefs.getLanguage(context))
return AppUtils.updateLocale(context, languageCode)
}
In AppUtils updateLocale function is like that;
@JvmStatic
fun updateLocale(context: Context, languageCode: String): Context {
val locale = Locale(languageCode)
Locale.setDefault(locale)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResourcesLocale(context, locale)
} else {
updateResourcesLocaleLegacy(context, locale)
}
}
private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
configuration.setLayoutDirection(locale)
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val configuration = context.resources.configuration
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
I hope your problem can be solved with that answer :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With