我有同样的要求。我检查了Android代码,发现
- 开关忽略应用于可绘制拇指形状的任何垂直边距/填充(因此拇指始终触摸轨道的顶部和底部)
- 拇指的宽度是通过取水平填充 + 开启和关闭文本的最大宽度来计算的。
这使得制作圆形拇指非常困难。
但是,如果您将拇指可绘制对象指定为可绘制图层的唯一原因是能够为可绘制对象的单层指定填充,则可以获得所需的效果。
拇指选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<!--
NOTE
We want a thumb with padding around it inside the track.
Sadly, a switch draws its track and thumb with the same height ignoring
any padding of the drawable, so using a shape with padding does not work.
To overcome, we apply a trick. We create layer list because the
LayerListDrawable draws itself with taking the top, left, right, bottom
values into account.
-->
<layer-list>
<item
android:top="@dimen/switch_thumb_padding"
android:left="@dimen/switch_thumb_padding"
android:right="@dimen/switch_thumb_padding"
android:bottom="@dimen/switch_thumb_padding">
<!--
NOTE
No need to specify size because:
- The thumb fills the track in height.
- The thumb width is determined from thumb max(on, off) text +
text padding + drawable padding.
-->
<shape android:shape="oval">
<solid android:color="@color/switch_thumb"/>
<!-- NOTE did not work, had to set Switch's thumbTextPadding to the radius -->
<!--
<padding android:right="@dimen/switch_thumb_radius"
android:left="@dimen/switch_thumb_radius"/>
-->
</shape>
</item>
</layer-list>
</item>
</selector>
我将开关的开关文本设置为空(实际上设置为“”以防止有关空资源的警告)。
追踪:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false">
<shape android:shape="rectangle">
<size android:height="@dimen/switch_track_height"/>
<corners android:radius="@dimen/switch_thumb_radius"/>
<solid android:color="@color/switch_track_off"/>
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<size android:height="@dimen/switch_track_height"/>
<corners android:radius="@dimen/switch_thumb_radius"/>
<solid android:color="@color/switch_track_on"/>
</shape>
</item>
</selector>
开关方式:
<style name="CustomSwitch">
<!-- NOTE this way the switch will be as width as required minimally -->
<item name="android:switchMinWidth">0dp</item>
<item name="android:track">@drawable/switch_track</item>
<item name="android:thumb">@drawable/switch_thumb</item>
<item name="android:textOff">@string/switch_thumb_off</item>
<item name="android:textOn">@string/switch_thumb_on</item>
<!-- NOTE if set to 0dp, the thumb was not visible even with padding
of the thumb drawable set to -->
<item name="android:thumbTextPadding">@dimen/switch_thumb_radius</item>-->
<!--<item name="android:thumbTextPadding">0dp</item>-->
</style>
最后,尺寸:
<dimen name="switch_track_height">30dp</dimen>
<dimen name="switch_thumb_radius">15dp</dimen>
<dimen name="switch_thumb_padding">2dp</dimen>
所以唯一“棘手”的事情是保持高度 = 半径 * 2。