Brandon
Brandon

Reputation: 146

How to know if a switch is on/off in android Switch Preference

i want to know how can i know if the switch is on/off to perform an action depending on the state of the switch

enable_social_recommendations = (Preference)  findPreference("enable_social_recommendations");
enable_social_recommendations.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {

    // here what should i do to know if the switch is on or off???

    return true;


}});

Upvotes: 1

Views: 794

Answers (2)

krossovochkin
krossovochkin

Reputation: 12122

Do the following:

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (newValue instanceof Boolean) {
        boolean isChecked = (boolean) newValue;
        // do whatever you want to do with this
    }
    return true;
}});

instanceof Boolean actually is not required, as newValue will be Boolean. But it is just to make sure that nothing bad can ever happen.

Upvotes: 3

Incinerator
Incinerator

Reputation: 2807

Use the newValue parameter that is passed to your changeListener.

Upvotes: 0

Related Questions