Rafael Lima
Rafael Lima

Reputation: 3535

how to turn on SwitchPreference programatically on Android

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

Upvotes: 1

Views: 2386

Answers (3)

Googlian
Googlian

Reputation: 6723

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);

Upvotes: 4

TheWanderer
TheWanderer

Reputation: 17834

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

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

Upvotes: 1

Jim
Jim

Reputation: 10278

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?

Upvotes: 0

Related Questions