我有一个带有4个片段的ViewPager,在其中一个片段上我可以选择用户选择语言,一旦当前片段上的选定文本应该更新以反映所选语言。我的布局xml文件中的所有内容都没有硬编码,而是从strings.xml文件填充。我有本地化的strings.xml文件。
以下是使用的算法:
以下是代码:
LangSelectionFragment.java (当前片段)
@OnClick({R.id.english_radio_button, R.id.hindi_radio_button})
public void onLanguageSelection(RadioButton radioButton) {
switch (radioButton.getId()) {
case R.id.english_radio_button:
updateLocaleForEnglish();
break;
case R.id.hindi_radio_button:
updateLocaleForHindi();
break;
}
}
private void updateLocaleForEnglish() {
LocaleManager.updateLangIsoCodeInPreferences(EnglishISOCode, getActivity());
LocaleManager.updateLocale(EnglishISOCode,getResources());
localRefreshActor.refreshFragmentsLocale();
}
private void updateLocaleForHindi() {
LocaleManager.updateLangIsoCodeInPreferences(HindiISOCode, getActivity());
LocaleManager.updateLocale(HindiISOCode,getResources());
localRefreshActor.refreshFragmentsLocale();
}
OnBoardingActivity.java (Parent Activity / localeRefreshActor)
@Override
public void refreshFragmentsLocale() {
Fragment currentFragment = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem()); // returns LangSelectionFragment
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
fragTransaction.remove(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
LocaleManager (在首选项中存储所选语言,更新区域设置)
public class LocaleManager {
private static final String AppLangIsoCodeKey = "appLangIso";
public static void updateLangIsoCodeInPreferences(String languageIsoCode, Context context) {
PreferencesManager.initializeInstance(context);
PreferencesManager preferencesManager = PreferencesManager.getInstance();
preferencesManager.setStringValue(languageIsoCode, AppLangIsoCodeKey);
}
public static String getLangFromPreferences(Context context) {
PreferencesManager.initializeInstance(context);
PreferencesManager preferencesManager = PreferencesManager.getInstance();
return preferencesManager.getStringValueForKey(AppLangIsoCodeKey);
}
public static void updateLocale(String languageIsoCode, Resources res) {
if(languageIsoCode != null && languageIsoCode.equalsIgnoreCase("")){
return;
}
Locale locale = new Locale(languageIsoCode);
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);
}
}
问题是 -
根据语言,它不会更新当前片段上的文本 选中:(
我在这里错过任何东西吗?请建议。