yawers
yawers

Reputation: 223

Styling a switch

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?

Upvotes: 2

Views: 105

Answers (1)

tachyonflux
tachyonflux

Reputation: 20211

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>

Upvotes: 2

Related Questions