0

I've a settings fragment which load a xml with a default settings page, I also added one click listener to one specific preference

   @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.settings);
       preferences.findPreference(getString(R.string.pref_custom_list)).setOnPreferenceChangeListener(this);
//other stuff.....

this works fine, when user clicks triggers an event and i can check some info about the switch including deny the change...

But i would like to turn on/off other switches in the same screen when this even happen

i tried to

   preferences.findPreference(getString(R.string.xpto)).setEnabled(true);

but it doesn't turn any switch on or off... it just set the view enabled or disabled for clicks

if i do something like PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("xpto",true).apply();

It does change the preference, but the changes are not loaded to the screen so user doesn't know

how can i switch some preference on or off programatically and make it reflect to the preference screen

Rafael Lima
  • 3,079
  • 3
  • 41
  • 105

3 Answers3

3

You can use SwitchPreferenceCompat.

<SwitchPreferenceCompat
    app:key="key"
    app:title="Some Confs" />

Try this in your fragment if you are using SwitchPreferenceCompat as above.

SwitchPreferenceCompat switchPref = findPreference("key");
switchPref.setChecked(true);
Googlian
  • 6,077
  • 3
  • 38
  • 44
1

You're looking for setChecked(), not setEnabled():

preferences.findPreference(getString(R.string.xpto)).setChecked(true);
TheWanderer
  • 16,775
  • 6
  • 49
  • 63
0

I think you need to implement a listener when the SharedPreferences change.

SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
                       SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    // change the Switch Preference state here
    }
};

Then when the prefs change, you can change the user's screen to match it.

For your reference:

How to detect if changes were made in the preferences?

Jim
  • 10,172
  • 1
  • 27
  • 36
  • i wasn't clear in my question, i do get the events properly... what i dont know is how to turn on OTHER preferences besides the one clicked – Rafael Lima Nov 30 '18 at 02:17