Summary: When the theme is changed on the Select a Language, History, and Change App Language screens, the titles switch from the selected language to English, causing inconsistency in the language settings. Steps to Reproduce: Open the app and set the language to a non-English language (e.g., Spanish, French, etc.). Navigate to any of the following screens: Select a Language History Change App Language Change the theme (e.g., switch between light and dark mode). Observe that the titles on these screens change from the selected language to English after the theme changed.
private void updateLocale(String langCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
LocaleListCompat appLocale = LocaleListCompat.forLanguageTags(langCode);
AppCompatDelegate.setApplicationLocales(appLocale);
} else {
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
}
}
To ensure locale persistence across theme changes, Android 13+ (TIRAMISU) uses AppCompatDelegate.setApplicationLocales(), while pre-Android 13 relies on updating the Configuration. First, store the selected language in SharedPreferences:
SharedPreferences prefs = getSharedPreferences("Settings", MODE_PRIVATE);
prefs.edit().putString("Lang", langCode).apply();
In updateLocale()
, apply the locale based on Android version:
private void updateLocale(String langCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
LocaleListCompat appLocale = LocaleListCompat.forLanguageTags(langCode);
AppCompatDelegate.setApplicationLocales(appLocale);
} else {
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
}
To ensure the locale is restored when the activity restarts, override attachBaseContext()
in BaseActivity
:
@Override
protected void attachBaseContext(Context newBase) {
Locale locale = new Locale(getSavedLangCode(newBase));
Configuration config = newBase.getResources().getConfiguration();
config.setLocale(locale);
super.attachBaseContext(newBase.createConfigurationContext(config));
}
Finally, after a theme change, force recreation to apply both locale and theme updates correctly:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
recreate();
By combining these methods, the app maintains the selected language across theme changes without inconsistencies