修改原生Switch组件的样式
通过修改Switch组件的布局属性来修改样式,今天要实现下图所示的2种状态
主要是通过设置track和thumb这2个属性,前者是设置开关的背景图,后者是设置开关的滑块图.先来看看switch组件的使用
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:thumb="@drawable/selector_switch_thumb"
android:track="@drawable/selector_switch_truck"
/>
我们都知道switch是有两种状态的,即开启和关闭这两种状态,因此我们可以考虑采用selector选择器的方式来实现不用状态的样式,因此我这里就用到了2个选择器:
selector_switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" >
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="22dp"
android:height="22dp"/>
<solid android:color="@color/color_white"/>
<stroke android:width="2dp" android:color="@color/color_FA4949"/>
</shape>
</item>
<item android:state_checked="false" >
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="22dp"
android:height="22dp"/>
<solid android:color="@color/color_white"/>
<stroke android:width="2dp" android:color="@color/color_CCCCCC"/>
</shape>
</item>
</selector>
滑块的预览效果:
selector_switch_truck.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" >
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="44dp"
android:height="22dp"/>
<solid android:color="@color/color_FA4949"/>
<corners android:radius="22dp"/>
</shape>
</item>
<item android:state_checked="false" >
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="44dp"
android:height="22dp"/>
<solid android:color="@color/color_CCCCCC"/>
<corners android:radius="22dp"/>
</shape>
</item>
</selector>
背景的预览效果:
注意:
switch的宽高是受thumb的高度决定的.