我正在使用偏好设置并面临这样的麻烦:我无法理解为什么在点击首选项按钮onPreferenceClick(Preference preference)
时调用方法onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
的原因我正在更改设置。
在类SettingsActivity
中它工作正常(我也有一个问题:为什么else
语句永远不会是真的?)但是我需要它来通知更改并重新创建我的活动。
班级SettingsActivity
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mSharedPreferences = this.getSharedPreferences("Launcher", Context.MODE_PRIVATE);
Preference clear = findPreference("clear_fav");
clear.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals("clear_fav")) {
Log.d("tag", "LOL");
editor = mSharedPreferences.edit();
editor.putBoolean("clearFavourite", true);
editor.apply();
return true;
} else {
Log.d("tag", "NO LOL");
editor = mSharedPreferences.edit();
editor.putBoolean("clearFavourite", false);
editor.apply();
}
return false;
}
});
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
int portrait = 0;
int landscape = 0;
editor = mSharedPreferences.edit();
if (sharedPreferences.getString("icons_amount", "").equals("1")) {
portrait = 4;
landscape = 6;
} else if (sharedPreferences.getString("icons_amount", "").equals("2")) {
portrait = 5;
landscape = 7;
}
if (sharedPreferences.getString("themes", "").equals("1")) {
editor.putBoolean("theme", true);
} else if (sharedPreferences.getString("themes", "").equals("2")) {
editor.putBoolean("theme", false);
}
editor.putInt("portrait", portrait);
editor.putInt("landscape", landscape);
editor.apply();
}
在班级MyActivity
中:
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d("tag", "RECREATE from Pref Changed");
recreate();
}
@Override
public boolean onPreferenceClick(Preference preference) {
Log.d("tag", "RECREATE from Click");
recreate();
return true;
}
}
preferences.xml
:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:defaultValue="default_hide"
android:key="hide_fav"
android:title="Hide Favourites" />
<Preference
android:defaultValue="default_clear_fav"
android:key="clear_fav"
android:title="Clear Favourites" />
<ListPreference
android:defaultValue="default_icons"
android:entries="@array/tableListArray"
android:entryValues="@array/tableListValues"
android:key="icons_amount"
android:title="Table" />
<ListPreference
android:defaultValue="default_theme"
android:entries="@array/themeListArray"
android:entryValues="@array/themeListValues"
android:key="themes"
android:title="Theme" />
<EditTextPreference
android:key="uri_amount"
android:title="Uri"/>
<Preference
android:defaultValue="default_clear_uri"
android:key="clear_uri"
android:title="Clear Uri" />
</PreferenceScreen>