通常修改默认的switch样式即可,主要用到两个属性
thumb
track
先看下效果图
![](https://img.haomeiwen.com/i5468551/5cce5bf3aed1596a.png)
先创建selector选择器来区别开关不同状态下显示样式
<!-- 底层下滑条的样式选择器,不同状态下,底下下滑条的颜色 switch_track.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_green_track" android:state_checked="true"/>
<item android:drawable="@drawable/switch_gray_track"/>
</selector>
<!-- switch_green_track.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 高度40 -->
<size android:height="20dp"/>
<!-- 圆角弧度 20 -->
<corners android:radius="4dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#d8d6d9"
android:startColor="#d8d6d9" />
</shape>
<!-- switch_gray_track.xml-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 高度30 此处设置宽度无效-->
<size android:height="20dp"/>
<!-- 圆角弧度 15 -->
<corners android:radius="4dp"/>
<!-- 变化率 定义从左到右的颜色不变 -->
<gradient
android:endColor="#949393"
android:startColor="#949393" />
</shape>
<!-- 按钮的选择器,不同状态下的时候,按钮不同的颜色 switch_thumb.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:drawable="@drawable/switch_green_thumb" />
<item android:drawable="@drawable/switch_gray_thumb" />
</selector>
<!-- switch_green_thumb.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 高度40 -->
<size android:height="20dp" android:width="25dp"/>
<!-- 圆角弧度 20 -->
<corners android:radius="4dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#0acc0a"
android:startColor="#0acc0a" />
<stroke android:width="1dp"
android:color="#0acc0a"/>
</shape>
<!-- switch_gray_thumb.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<size android:height="20dp" android:width="25dp"/>
<!-- 圆角弧度 -->
<corners android:radius="4dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#e1e5e1"
android:startColor="#e1e5e1" />
<stroke android:width="1dp"
android:color="#e1e5e1"/>
</shape>
最后在布局文件中加入开个按钮。
<Switch
android:id="@+id/setting_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dp"
android:switchMinWidth="25dp"
android:textOff=" "
android:textOn=" "
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_track" />
网友评论