Android Switch thumb image stretched

2019-08-28 23:55发布

问题:

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?

回答1:

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