我有一个下拉列表,用户可以选择
English
或
Spanish
语言。
问题是,在语言更改时,它会将日期、时间、进度对话框文本转换为西班牙语或英语,但我定义的字符串不会转换为指定的语言。
虽然它们在单击1或2次后会转换,所以当我单击
ES
它不会将字符串更改为
锿
,但随后我单击
EN
,它将工作并将所有字符串转换为
锿
,这不是期望的结果。
当用户点击任何语言时,我执行以下代码。
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());
}
这个
load language
方法执行这些操作。
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();
}
在每个活动中,我都添加了以下代码。
@Override
protected void attachBaseContext(Context newBase) {
Locale locale = new Locale(LanguagePreference.getInstance().getUserLanguage(newBase));
Context context = ContextWrapper.wrap(newBase, locale);
super.attachBaseContext(context);
}
下面是我的上下文包装类。
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);
}}