SwitchPreference onChecked/onClick Listener

后端 未结 3 1388
清歌不尽
清歌不尽 2021-02-05 02:51

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

相关标签:
3条回答
  • 2021-02-05 03:25

    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.

    0 讨论(0)
  • 2021-02-05 03:37

    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;
                        }
                    });
                }
            }
    
    }
    
    0 讨论(0)
  • 2021-02-05 03:40

    Use setOnPreferenceChangeListener() instead of setOnPreferenceClickListener().

    0 讨论(0)
提交回复
热议问题