问题
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" />
回答1:
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").
回答2:
You have to call the listener yourself. Instead of notifyChanged(), try callChangeListener(val) as seen here:
NumberPickerPreference
来源:https://stackoverflow.com/questions/12737724/how-to-use-setonpreferencechangelistener-for-quietlycoding-numberpicker