Search code examples
androidandroid-layoutswitchpreference

How to change icon of SwitchPreference when it changes state from off to on?


I would like to change the icon in my SwitchPreference (e.g. for enabling notification sound) once the state is changed from on to off and vice versa.

This is the code of my SwitchPreference:

<SwitchPreference
    android:key="@string/pref_key_sound"
    android:id="@+id/pref_key_sound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:title="@string/pref_sound"
    android:summaryOff="Off"
    android:summaryOn ="On"
    android:showText="true"
    android:defaultValue="false"
    android:icon="@mipmap/ic_volume"
/>

As you can see here I set just a fixed icon.


Solution

  • I solved the problem.

    In my PreferenceActivity I registered my SharedPreferences to listen for changes like this: prefs.registerOnSharedPreferenceChangeListener.

    In the onSharedPreferenceChangedcallback I just checked if the key was corresponding to the one of my SwitchPreference and if yes, I checked whether it was selected or not by getting the boolean value stored in the SharedPreferences:

    boolean isOn = sharedPreferences.getBoolean(getString(R.string.pref_key_sound), true);

    Afterwards I obtained a reference to my SwitchPreference:

    SwitchPreference switchPreference = (SwitchPreference) settingsFragment.findPreference("pref_key_sound");
    

    and simply changed the icon based on the boolean isOn since the value is updated each time the switch is pressed:

    if (isOn) {
    
         switchPreference.setIcon(R.mipmap.ic_volume);
    
       } else {
    
          switchPreference.setIcon(R.mipmap.ic_volume_off);
    
       }
    

    Simple as that! :) Hope it is clear!