I have a drop down, user can either choose English
or Spanish
language.
The issue is that on language changed, it converts date, time, progress dialog text to spanish or english, but the strings that i defined are not converted to the specified language.
Although they do convert after 1 or 2 clicks, so when i click on ES
it won't change strings to ES
, but then i click on EN
, it will work and convert all string to ES
, which is not the desired result.
When user taps on any language i execute following code.
languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedLanguage= getResources().getStringArray(R.array.language_array)[i];
loadLanguage(selectedLanguage.toLowerCase());
}
The load language
method perfoms these operations.
public void loadLanguage(String language){
String languageToLoad = language;
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
recreate();
}
At each activity i have added following code.
@Override
protected void attachBaseContext(Context newBase) {
Locale locale = new Locale(LanguagePreference.getInstance().getUserLanguage(newBase));
Context context = ContextWrapper.wrap(newBase, locale);
super.attachBaseContext(context);
}
Following is my Context Wrapper class.
public static ContextWrapper wrap(Context context, Locale newLocale) {
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(newLocale);
LocaleList localeList = new LocaleList(newLocale);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = newLocale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return new ContextWrapper(context);
}}