你可以像这样定义用于背景和开关部分的可绘制对象:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
现在,您需要创建一个选择器,定义切换图形的不同状态。以下是来自Android源代码的副本:
<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>
这定义了滑块图像的样式,即在背景上移动的图像。滑块有四个NinePatch图像:
未激活版本(Android正在使用的xhdpi版本)
已按下的滑块:
已激活的滑块(开启状态):
默认版本(关闭状态):
还有三种不同的背景状态,在以下选择器中定义:
<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>
这是已停用的版本:
这是焦点版本:
还有默认版本:
要创建一个样式化的开关,只需要创建这两个选择器,将它们设置为您的开关视图,然后将这七个图像更改为您想要的样式。