The app supports os 8.0+
I have added the values-ar
folder with support for strings.xml
. If I change the language from phone settings to arabic, the app loads the correct resources.
If I set the default locale at runtime in Application
class, it fails to load the specific ("ar") resources.
This is how I change conf (on Application
class):
fun changeDefaultLocale() {
Locale.setDefault(Locale("ar")
val configuration = resources.configuration
configuration.setLocale(locale)
this.createConfigurationContext(configuration)
}
What I have tried:
- rename
values-ar
tovalues-ar-rEG
- add
resConfigs "en", "ar"
onapp/build.gradle
- add
android:configChanges="locale"
toManifest/<application
- use
Locale("ar","AE")
orLocale("ar","EG")
I had put a break point on the row after I called the above changeDefaultLocale()
fun:
Why it doesn't load the correct resource file? I repeat, if I change it from the phone settings it works correctly.
UPDATE
Using @Nurbol response I have updated the BaseActivity
as below, and it's working fine. My problem now is:
Activity A
-> Activity B (here I switch the locale)
, then if I press back and the sistem restores Activity A
, it has the old configuration, and the old locale. How to overcome that?
override fun attachBaseContext(base: Context) {
super.attachBaseContext(updateBaseContextLocale(base))
}
private fun updateBaseContextLocale(context: Context): Context {
val locale = Locale("ar")
Locale.setDefault(locale)
return updateResourcesLocale(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)
}