我正在尝试创建一个自定义开关按钮,该按钮的拇指约为其轨道的 75%(宽度)。我不想使用图像,只想使用可绘制的形状、样式等。到目前为止,我已经完成了以下操作:
activity_main.xml
<Switch
android:id="@+id/onOffSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:track="@drawable/switch_custom_track"
android:thumb="@drawable/switch_custom_thumb"
android:showText="true"
android:textOff="Off"
android:textOn="On"/>
switch_custom_track.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/switch_custom_track_on" />
<item android:state_checked="false" android:drawable="@drawable/switch_custom_track_off" />
</selector>
switch_custom_track_on.xml
<shape
android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="20dp" />
<solid android:color="#00b800" />
<size android:width="90dp" android:height="40dp" />
</shape>
switch_custom_track_off.xml
<shape
android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="20dp" />
<solid android:color="#fd491d" />
<size android:width="90dp" android:height="40dp" />
</shape>
switch_custom_thumb.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/switch_custom_thumb_on" />
<item android:state_checked="false" android:drawable="@drawable/switch_custom_thumb_off" />
</selector>
switch_custom_thumb_on.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="20dp" />
<solid android:color="#ffffff" />
<size android:width="70dp" android:height="40dp" />
<stroke android:width="2dp" android:color="#00b800" />
</shape>
switch_custom_thumb_off.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="20dp" />
<solid android:color="#ffffff" />
<size android:width="70dp" android:height="40dp" />
<stroke android:width="2dp" android:color="#fd491d" />
</shape>
使用上面的代码,我得到了这个:
所以拇指宽度是轨道的 50%。请注意“switch_custom_track_off.xml”中 size 元素中“90dp”的宽度和“switch_custom_thumb_off.xml”中 size 元素中“70dp”的宽度。我预计拇指的相对大小(到轨道)应该是 70dp/90dp=77%。然而,可以清楚地看到轨道扩大到拇指大小的两倍。
那么是否可以制作“完全自定义”大小的拇指和轨道?如果是,你能帮我达到预期的结果吗?