OnPreferenceChangeListener未调用

时间:2016-03-21 16:21:45

标签: android sharedpreferences android-preferences

当用户点击首选项并在摘要中显示所选日期时,我尝试启动日期选择器片段。

但是,当首选项值更改时,不会调用OnPreferenceChangeListener。我确认价值确实发生了变化。

我做错了吗?

这是SettingsFragment

// Configure setting start date
    Preference startDatePref = findPreference(getString(R.string.pref_start_date));
    startDatePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            DialogFragment startFragment = DatePickerFragment.newInstance(DatePickerFragment.PICK_START);
            startFragment.show(((AppCompatActivity) getActivity()).getSupportFragmentManager(), "Pick Start Date of Semester");
            return true;
        }
    });
    // Update the summary when date is picked
    startDatePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            preference.setSummary(newValue.toString());
            Log.d("pref change", "called!");
            return true;
        }
    });

的DatePicker

public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    SharedPreferences pref = getActivity().getSharedPreferences(
            getActivity().getString(R.string.date_info_file), Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    if (mType == PICK_START) {
        editor.putInt(getString(R.string.start_date_year), year);
        editor.putInt(getString(R.string.start_date_month), monthOfYear);
        editor.putInt(getString(R.string.start_date_day), dayOfMonth);
        UniData.setDataStatus(getActivity(), UniData.START_DATE, true);

        // Change the preference used in preferences.xml so that the onChange listener will be called
        SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(getContext());
        SharedPreferences.Editor editDefault = defaultPref.edit();
        editDefault.putString(getString(R.string.pref_start_date), year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        editDefault.commit();

        Log.d(LOG_TAG, "Start Picked: " + year + " " + monthOfYear + " " + dayOfMonth);
    }
    ... 
    editor.commit();

的preferences.xml

<PreferenceCategory
    android:key="pref_key_schedule_settings"
    android:title="Schedule">
    <Preference
        android:defaultValue=""
        android:key="pref_start_date"
        android:summary="For the app to determine odd and even week."
        android:title="Set start date of semester"/>
</PreferenceCategory>

0 个答案:

没有答案