Reputation: 840
I'm trying to create Preference Screen with a Checkbox control.
<CheckBoxPreference android:summaryOn="@string/mySummaryOn"
android:summaryOff="@string/mySummaryOff"
android:key="myCB"
android:title="my checkbox"/>
I want to get this Boolean value when ever its getting changed.
In my Application i have done as below implementing OnSharedPreferenceChangeListener
public boolean cbValue;
@Override
public void onCreate() {
// The following line triggers the initialization of ACRA
ACRA.init(this);
prefs=PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
super.onCreate();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
//FacebookStatus=prefs.getBoolean("myCB", true);
Toast.makeText(getBaseContext(), "Shared Preference Changes ",Toast.LENGTH_LONG ).show();
}
onSharedPreferenceChanged method is not at all called even when i toggle check box in pref screen.
If i need to get value from Shared preference each time when value is changed wat should i do?
Upvotes: 2
Views: 6790
Reputation: 11
SwitchPreference switchPref = (SwitchPreference)findPreference("switchPref");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean beforeChange = ((SwitchPreference) preference).isChecked();
boolean afterChange = !beforeChange;
((SwitchPreference) preference).setChecked(afterChange);
// Toast.makeText(getContext(), ""+afterChange, Toast.LENGTH_SHORT).show();
return false;
}
});
If you override onPreferenceChange(), the checked status doesn't change when you clicked the switch.
Don't forget to add switchPref.setChecked(!isChecked()).
Upvotes: 1
Reputation: 4781
You can read the new value directly with the SharedPreferences
parameter object. If you know that the key is from the CheckBoxPreference
you can just read the value:
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key == getString(R.string.CheckBoxKeyId)) {
boolean myBool = sharedPreferences.getBoolean(key, false);
// do stuff
}
}
This saves you adding an OnPreferenceChangeListener
for each of the CheckBoxPreference
you might have.
Upvotes: 0
Reputation: 423
Instead of using OnSharedPreferenceChangeListener
:
Add to your preference activity's onCreate
method following line: Preference myCheckbox = findPreference("myCB")
Then apply a listener to myCheckbox
object: myCheckbox.setOnPreferenceChangeListener(myCheckboxListener)
Code of the listener (as a class field):
private OnPreferenceChangeListener myCheckboxListener = new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Read new value from Object newValue here
return true;
}
};
Upvotes: 2