对于以下代码:
final SwitchPreference sp = (SwitchPreference) findPreference(getString(R.string.pref_key_reminder));
sp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
AlarmReceiver.scheduleAlarm(getActivity());
return true;
}
});
我需要更改开关偏好设置的值,但是preferance
中的值是进行更改之前的值。对象o
具有新值,但是如何在调用AlarmReceiver.scheduleAlarm
之前在首选项中设置该值。该方法使用首选项的值。
答案 0 :(得分:0)
您是正确的,在调用SwitchPreference
后,SharedPreferences
会更改基础的Preference.OnPreferenceChangeListener.onPreferenceChange
值,请参见SwitchPreference
中的代码:< / p>
private class Listener implements CompoundButton.OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!callChangeListener(isChecked)) { // callback here
// Listener didn't like it, change it back.
// CompoundButton will make sure we don't recurse.
buttonView.setChecked(!isChecked);
return;
}
SwitchPreference.this.setChecked(isChecked); // save value here
}
}
/**
* Sets the checked state and saves it to the {@link SharedPreferences}.
*
* @param checked The checked state.
*/
public void setChecked(boolean checked) {
// Always persist/notify the first time; don't assume the field's default of false.
final boolean changed = mChecked != checked;
if (changed || !mCheckedSet) {
mChecked = checked;
mCheckedSet = true;
persistBoolean(checked);
if (changed) {
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
}
}
然后在您拨打电话时:
AlarmReceiver.scheduleAlarm(getActivity());
并从SharedPreferences
检索值,您将获得旧值。因此,您可以例如使用AlarmReceiver.scheduleAlarm
将呼叫转移到Handler
:
handler.post(new Runnable() {
AlarmReceiver.scheduleAlarm(getActivity());
});