在我的安卓应用中,我有一个偏好设置活动,让用户可以覆盖应用的语言。为了实现这一点,我在每个活动的onResume()函数中调用此函数,然后重置内容视图:
public static void checkOverrideSystemLanguage(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
// Check if system's language setting needs to be overridden
boolean overrideSystemLanguage = prefs.getBoolean(context
.getString(R.string.pref_key_chkbx_override_system_language),
false);
if (overrideSystemLanguage) {
// Get language selection and possible languages
String localeString = prefs.getString(
context.getString(R.string.pref_key_list_languages), "");
List<String> possibleLanguages = Arrays.asList(context
.getResources().getStringArray(
R.array.pref_values_list_languages));
if (possibleLanguages.contains(localeString)) {
// Change language setting in configuration
Locale locale = new Locale(localeString);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
}
// Use default language
else {
overrideSystemLanguage = false;
}
}
// Use default language
if (!overrideSystemLanguage) {
context.getResources().updateConfiguration(
Resources.getSystem().getConfiguration(),
context.getResources().getDisplayMetrics());
}
}
在任何活动中,它都能完美运行。然而,在偏好设置活动中,在用户更改语言时,它不会立即更新,因为没有 setContentView() 方法。用户必须返回到上一个活动并重新启动偏好设置活动才能看到语言更改的反映。
我在 onPreferenceChange() 监听器中尝试了以下操作:
Updating the configuration, removing and readding the preferences:
checkOverrideSystemLanguage(this); // Remove all preferences and add them to update the language getPreferenceScreen().removeAll(); addPreferencesFromResource(R.xml.preferences);
Updating the configuration and calling onCreate(null)
Finishing and restarting the activity
finish(); startActivity(new Intent(this, PreferencesActivity.class));