When my Activity gets started I want to make sure it is using the correct language. I currenttly use this code to do that:
override fun attachBaseContext(newBase: Context) {
val newContext = updateBaseContextLocale(newBase)
super.attachBaseContext(newContext)
}
private fun updateBaseContextLocale(context: Context): Context {
val locale = getMyLocale() // getMyLocale() gets the locale that should be used.
Locale.setDefault(locale)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResourcesLocale(context, locale)
} else {
updateResourcesLocaleLegacy(context, locale)
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val configuration = context.resources.configuration
configuration.setLocale(locale)
return context.createConfigurationContext(configuration)
}
@Suppress("DEPRECATION")
private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
This produces the correct result on Android 8 and newer, but for some reason the language stays unchanged on older versions of Android.
Calling the updateBaseContextLocale(context: Context)
function from onCreate
doesn't seem to change anything either.
I have already seen this question but I failed to turn the answers there into a working solution.
What am I doing wrong?
Edit:
My ultimate goal with this is to change the language of just that Activity but if changing the language of one Activity alone is not possible, changing the language of the entire App is also acceptable.