I am trying to customize Switch. I used xml files to achieve that
switch_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cd_filled_toggle_round_bg" android:state_checked="true"/>
<item android:drawable="@drawable/cd_filled_toggle_round_bg" android:state_checked="false"/>
<item android:drawable="@drawable/cd_filled_toggle_round_bg"/>
</selector>
and track_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cd_filled_toggle_bg" android:state_checked="true"/>
<item android:drawable="@drawable/cd_filled_toggle_white_bg" android:state_checked="false"/>
<item android:drawable="@drawable/cd_filled_toggle_white_bg"/>
</selector>
and the code for switch is
<Switch
android:id="@+id/toggle_email_diss_invi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:textOff=""
android:textOn=""
android:thumb="@drawable/switch_bg_selector"
android:thumbTextPadding="25dp"
android:track="@drawable/track_bg_selector"
/>
the background image I used is sliced for all xxhdpi, xhdpi, hdpi and mdpi but the problem is that the images are getting stretched. I spent many hours to resolve this issue but didn't find appropriate solution. I am attaching the screenshot that how my switch is looking.
and how it should look like this
below are my drawable i am using
I was implementing the same switch button.I also end up with a streched background as yours.The reason for this streching is the fact that image of thumb is not compatible with track images. The thumb image in my case was having too much left and right padding.I also tried 9patch images but it didn't worked. I came up following solutions:
But finally I found the best solution and used it instead of above workarounds
copy these xml files into your drawable folder.
switch_thumb.xml
switch_thumb_selector.xml
switch_track_off.xml
switch_track_on.xml
switch_track_selector.xml
Finally You can use the switch as follows:
Now you can change the color of background of tracks to get desired result. Hope this helps!!!