How can I style an Android Switch?

Glenn.nz picture Glenn.nz · Apr 12, 2012 · Viewed 120.7k times · Source

The switch widget introduced in API 14 is styled by default with holo theme. I want to style it slightly different, changing its colors and shape a bit for branding reasons. How does one go about this? I know it must be possible, as ive seen the difference between default ICS and Samsung's touchwiz theme

enter image description here

I assume I'll need some state drawables, and I've seen a few styles in http://developer.android.com/reference/android/R.styleable.html with Switch_thumb and Switch_track that look like what I might be after. I just don't know how to go about using them.

I'm using ActionbarSherlock if that makes a difference. Only devices running API v14 or above will be able to use a switch at all, of course.

Answer

Janusz picture Janusz · Apr 13, 2012

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.