在进行更改之前会触发OnPreferenceChangeListener

时间:2018-07-10 03:13:11

标签: android

对于以下代码:

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之前在首选项中设置该值。该方法使用首选项的值。

1 个答案:

答案 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());
});