2

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.

implmentor
  • 1,386
  • 4
  • 21
  • 32
APagano
  • 108
  • 5
  • That takes quite a bit of work to accomplish. This might help you. http://stackoverflow.com/questions/21235829/custom-switchpreference-in-android In cases where I have to do this sort of customizations I resort to using custom classes. – JanithaR Aug 18 '15 at 07:52
  • @JanithaR There is a bit easier solutions- Instead of making custom layout and apllying it. You can apply the thumb and track attributes trough styles. Your Theme: – X3Btel Aug 18 '15 at 08:11
  • @X3Btel Hmmm... I guess that's easier but I believe this leads to issues in many cases. I cannot exaclty recall why I stuck with creating custom classes now, sorry about that. Anyways if that's the solution you're suggesting then better educate him how to do the 9 patch drawables correctly as well. http://stackoverflow.com/questions/10118050/how-can-i-style-an-android-switch – JanithaR Aug 18 '15 at 08:21
  • Creating a custom selector like: shouldn't be enough? – APagano Aug 18 '15 at 09:49

1 Answers1

2

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!

APagano
  • 108
  • 5