I want to get value of a checkboxpreference. which method is suitable for listen to preference?
And what's real difference between OnPreferenceChangeListener and OnSharedPreferenceChangeListener ?!
UPDATE Why onSharedPreferenceChanged not called?
public class Setting extends PreferenceActivity implements
OnSharedPreferenceChangeListener // ,OnPreferenceChangeListener
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);// deprecated warning
}
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {// DO Stuff
}
@Override
protected void onResume() {
super.onResume();
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
The difference between these 2 is that OnPreferenceChangeListener
is a callback called only when its preference changes (applies to a single key), while OnSharedPreferenceChange
is a callback called whenever any of the preferences in that SharedPreferences
object changes (applies to all keys).
So, in your case, you need to use the OnPreferenceChangeListener
with your CheckBoxPreference
.
Here is an example:
Preference ckboxPref = this.findPreference(CKBOX_PREF_KEY);
ckboxPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
//Do stuff
}
});
The method findPreference
does not work if you use fragments, but you aren't using any so it is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With