I\'ve been racking my brains all night but can\'t seem to accomplish this one small thing. I would like to add a SwitchPreference into my PreferenceActivity of an app. Below is
If you still haven't figured out a good way for doing this I have figured something out that doesn't create multiple calls to onPreferenceChange
which clicking the preference does. I wrote it in another question: dual functionality SwitchPreference.
Working code
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
SwitchPreference vibrateSwitch = (SwitchPreference) findPreference("notification_vibrate");
if (vibrateSwitch != null) {
vibrateSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference arg0, Object isVibrateOnObject) {
boolean isVibrateOn = (Boolean) isVibrateOnObject;
if (isVibrateOn) {
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(400);
}
return true;
}
});
}
}
}
Use setOnPreferenceChangeListener()
instead of setOnPreferenceClickListener()
.