Language of Android app changes after screen rotation

Viewed 136

I have an android app that contains only one activity that hosts all other fragments on the app. my application supports two languages (EN and AR), when I run the app with Arabic language and rotate my screen, some text resources become in English. I tried to overrides onConfigurationChanged inside the main activity to reset the language as follow:

@RequiresApi(Build.VERSION_CODES.N)
override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    // val currentAppLocale = Locale.getDefault().getLanguage()==>en
    setLocale(newConfig.locales[1].toString())
}

private fun setLocale( localelan:String) {
    val locale = Locale(localelan)
    Locale.setDefault(locale)
    val config = Configuration()
    config.locale = locale
    baseContext.resources.updateConfiguration(
        config,
        baseContext.resources.displayMetrics
    )
}

but the callback was not triggered, also I tried to put the call back inside the fragment and it was not triggered.

1 Answers

Orientation change calls onDestroy and onCreate again of the Activity. You need to save your values and reload them in order to preserve them.

private static final String LOCALE_KEY = "LocaleKey";

@Override
protected void onSaveInstanceState(final Bundle outState) {
    super.onSaveInstanceState(outState);
    
    // Save the state
     outState.putInt(LOCALE_KEY, getYourLocale);   
}

@Override
protected void onRestoreInstanceState(final Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    
    // Read the state
    locale = savedInstanceState.gettInt(LOCALE_KEY);
}
Related