0

I need a custom Switch in Android application. I'm using this code:

<Switch
    android:id="@+id/switchmode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true" 
    android:textOn=""
    android:textOff=""
    android:switchMinWidth="0dp"
    android:thumb="@drawable/switch_bg"
    android:track="@drawable/track_bg"
    android:layout_marginBottom="20dp" 
    android:layout_marginRight="20dp" />

track_bg file is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item                               android:drawable="@drawable/switch_track" />
</selector>

switch_bg file is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_enable" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_press" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_check_on" />
    <item                               android:drawable="@drawable/switch_enable" />
</selector>
  • switch_check_on is 32 x 31
  • switch_enable is 32 x 31
  • switch_press is 32 x 31
  • switch_track is 64 x 31

The result is a stretched image (it should be a circle but it is crushed):

https://www.dropbox.com/s/07iigspuh3dpfnh/switchstreched.jpg

Any obvious error?

Pang
  • 9,564
  • 146
  • 81
  • 122
andreasperelli
  • 1,034
  • 2
  • 11
  • 40

1 Answers1

0

Create 9-patch image and specify how it should be stretched by Android. You can read more here

Veaceslav Gaidarji
  • 4,261
  • 3
  • 38
  • 61
  • what should be patched ? the track file or thumb files ? – andreasperelli Jul 01 '14 at 09:28
  • 1
    both. open image 9-patch editor and check how it will be stretched by Android. Stretching don't depends on your switch work logic, but - android device resolution and density. So if you have 1 image resource for all resolutions and densities - make it 9-patch and it will be stretched by specified rules. – Veaceslav Gaidarji Jul 01 '14 at 09:32
  • look how it's realized in this sample project https://github.com/hearbeathorror/Switch-Compat-Changing-Colors/tree/master/SwitchCompatLibrary – Veaceslav Gaidarji Jul 01 '14 at 10:10