我想在用户更改语言或时间格式等设置后立即更新我的活动。这是我的代码:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String HOUR_FORMAT = "hourFormat";
public static final String LANGUAGE_CHOICE = "languageSelection";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("hourFormat")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(Boolean.toString(sharedPreferences.getBoolean(key, true)));
}
else if(key.equals("languageSelection")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, "English"));
}
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
这是preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="hourFormat"
android:title="@string/hour24"
android:summary="@string/hour24Explanation"
android:defaultValue="true" />
<ListPreference
android:key="languageSelection"
android:entries="@array/languageValues"
android:summary="@string/languageSelection"
android:entryValues="@array/languageValues"
android:title="@string/language" />
</PreferenceScreen>
这只有在我重新启动应用程序时才有效。但是我想在更改后立即更新它?(如果你愿意,我可以在我的应用程序中提供其他源代码,我知道有很多资源,但我无法让这个东西工作。)
我也认为我不太了解 Java 中的 xListener 概念。我读了很多,但你能澄清或提供额外的链接给我吗?提前致谢。