6

Developing application with List and Map data presentations. For switching between presentations should be used custom switch with images, like this:

enter image description here

How to create such custom switchcompat?

Vitalii
  • 10,091
  • 18
  • 83
  • 151
E I
  • 501
  • 4
  • 13

1 Answers1

0

Here is very good example:

ORIGINAL ANSWER

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.

Community
  • 1
  • 1
Anton A.
  • 1,718
  • 15
  • 37
  • thank you for answer! but this control should be like SwitchCompat (not like radio button) - should change status when user pulling it left to right and vice versa – E I Mar 02 '17 at 10:17