By following of what you want, to get icon changed by just create xml without handled programmatically is need much to do to accomplish, and still need some code in your java/kotlin.
Here what was i tried:
I've been try this way and it's worked, the icon changed, but once i said, this way is not recommended in my opinion. Handling icon change programmatically is better and more effective.
Adjust your SwitchPreference
<SwitchPreference
android:title="@string/psm_pinterest"
android:defaultValue="false"
android:key="@string/pref_social_pinterest"/>
First, in your Setting fragment/activity
Set layout to replace view of the SwitchPreference and create the switch listener too.
For example, like this:
SwitchPreference prefSocPin = (SwitchPreference) findPreference(getString(R.string.pref_social_pinterest));
prefSocPin.setWidgetLayoutResource(R.layout.pinterest_switch); // THIS IS THE KEY OF ALL THIS. HERE YOU SET A CUSTOM LAYOUT FOR PreferenceSwitch
prefSocPin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Here you can enable/disable whatever you need to
return true;
}
});
Second, create layout pinterest_switch.xml
For example, like this:
<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pinterest_switch_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textIsSelectable="false"
android:track="@drawable/pinterest_track"
android:thumb="@drawable/pinterest_thumb"/>
Third, in the drawable
Same with your first try, create xml in drawable for state listener, but this time you will create 2 items. Once for track, once for thumb.
pinterest_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_bg_focused" android:state_focused="true"/>
<item android:drawable="@drawable/switch_bg"/>
</selector>
pinterest_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_thumb_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/switch_thumb_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/switch_thumb_activated" android:state_checked="true"/>
<item android:drawable="@drawable/switch_thumb"/>
</selector>
I'm following this reference with some adjustment to your need.
In summary, change icon by just creating xml is a harder work and
uneffective way, in my opinion.
Well, still I'm trying to answer of what you want. Enjoy.