javaandroidandroid-preferencescheckboxpreference

Toggle return value for CheckboxPreference onClick


I need to find a way to toggle the return value when clicking my CheckboxPreference. I have already set a key in my settings.xml. The click works fine, I'm just curious about how to return a new value upon each click.

final Preference disableRemixingPref = (Preference) findPreference("disableRemixing");
        disableRemixingPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

                // I don't always want to return true here. Basically, on every click I want to return the opposite of what the selection was before.

                return true;
            }

        });

Solution

  • I managed to figure it out myself rather quickly. Did a few searches on toggling Boolean values: Cleanest way to toggle a boolean variable in Java?

        final Preference disableRemixingPref = (Preference) findPreference("disableRemixing");
        disableRemixingPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    
            boolean toggle = false;
            public boolean onPreferenceClick(Preference preference) {
                disableRemixingPref.setSelectable(true);
    
                // Disable remixing by default
                ParseUser currentUser = ParseUser.getCurrentUser();
                currentUser.put("remixByDefault", toggle);
                currentUser.saveInBackground();
    
                toggle = !toggle;
                return toggle;
            }
    
        });