2

I want to use a switch in my app, but I want it to have custom colors. Right now it doesn't show up at all.

Switch in my xml:

<Switch
    android:id="@+id/switch"
    android:track="@drawable/switch_track"
    android:thumb="@drawable/switch_thumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

switch_track.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@color/grey_light"/>
    <item android:state_pressed="true"  android:drawable="@color/grey_light"/>
    <item android:state_checked="true"  android:drawable="@color/accent_light"/>
    <item android:drawable="@color/grey_light"/>
</selector>

switch_thumb.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@color/grey"/>
    <item android:state_pressed="true"  android:drawable="@color/grey"/>
    <item android:state_checked="true"  android:drawable="@color/accent"/>
    <item android:drawable="@color/grey"/>
</selector>

Do I need to add icons for the selectors instead of colors or is there a way to just change the color?

eski
  • 7,917
  • 1
  • 23
  • 34
yawers
  • 223
  • 1
  • 4
  • 12

1 Answers1

2

If you are using the support library, you could use the material properties to color a SwitchCompat:

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

styles.xml:

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
    <item name="colorSwitchThumbNormal">@color/grey</item>
    <item name="colorControlActivated">@color/accent</item>
</style>
tachyonflux
  • 20,103
  • 7
  • 48
  • 67
  • Thank you, do you know if there is a way to color the track also? When it is not activated it is just white, and I have a white background. When it is activated it is colored correctly. – yawers Jun 02 '15 at 18:05
  • 1
    http://stackoverflow.com/questions/27845595/how-to-change-the-track-color-of-a-switchcompat – tachyonflux Jun 02 '15 at 19:20