How to use setOnPreferenceChangeListener for Quiet

2019-02-19 22:54发布

I want to detect when the value from the NumberPicker is changed. I have this code on my PreferenceActivity:

public class MainPrefs extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.addPreferencesFromResource(R.xml.main_preferences);
        this.findPreference("SMSSentLimit").setOnPreferenceChangeListener(
            new OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    TrackerService.updateStats(Long.decode(newValue.toString()));
                    return true;
                }
            });
        this.findPreference("NumberPickerLimit").setOnPreferenceChangeListener(
            new Preference.OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    Log.i("onPreferenceChange", "NumberPicker Changed");
                    Toast.makeText(getBaseContext(), "CHANGEEEED !!!",
                        Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
    }
}

The second one (findPreference("NumberPickerLimit")) is the NumberPicker and it is never called, if I change it to onPreferenceClickListener it works but I detect when I click the preference instead when I change the value.

Acording to source code it should be called:

public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                saveValue(mPicker.getCurrent());
                break;
            default:
                break;
        }
    }

private void saveValue(int val) {
    getEditor().putInt(getKey(), val).commit();
    notifyChanged();
}

What´s happening? Is it a bug?

EDIT Here is my XML:

<com.michaelnovakjr.numberpicker.NumberPickerPreference
            android:key="NumberPickerLimit"
            android:title="@string/NumberPickerTitle"
            android:summary="@string/NumberPickerSummary"
            picker:defaultValue="1"
            picker:startRange="1"
            picker:endRange="31" />

2条回答
Anthone
2楼-- · 2019-02-19 23:18

You have to call the listener yourself. Instead of notifyChanged(), try callChangeListener(val) as seen here:

NumberPickerPreference

查看更多
何必那么认真
3楼-- · 2019-02-19 23:35

Just looked at your xml file listed here, looks like you have android:key="demo.preference" there. Whereas in the code here, you're using findPreference("NumberPickerLimit").

查看更多
登录 后发表回答