转自:http://blog.youkuaiyun.com/u012585142/article/details/50756872
今天发现需要使用控件switch,但是需要自定义switch的样式,通过查阅资料,发现可以通过定义switch的thumb和track的图片来达到自定义switch样式的目的.现把相关的步骤记录下来,以备查阅。
其中1为所需样式,2为系统自定义样式
1、创建thumb(即来回滑动的滑动块)利用XML来定义一个drawable文件,命名为switch_thumb
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="25dp"
android:height="25dp">
</size>
<!-- 填充的颜色:这里设置滑动块为白色 -->
<solid android:color="@color/white" />
<!--<solid android:color="@color/theme_color" />-->
****<!-- 边框的颜色 :因为需要显示一点点背景色,所以设置了一个透明边框 -->**
<stroke
android:width="2dp"
android:color="@android:color/transparent" />**
<!--<corners android:radius="2dip" />-->
<corners android:radius="2dip" />
</shape>
2、track属性又该如何设置呢?
问题在于打开switch与关闭switch,switch的下面的滑道应该是不同的颜色,我们想到了可以用drawable的selector标签,利用switch的不同状态,来加载不同的drawable文件。我们查看官方switch文档,发现其有
void setChecked(boolean checked) Changes the checked state of this button.
这样一个方法,所以我们可以利用其state_checked状态,依据不同的状态来选择加载不同的drawable文件
1):首先,我们定义一个drawable文件:switch_track_on.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="@color/colorPrimary">
</solid>
<corners android:radius="2dip" />
</shape>
2):再定义一个drawable文件:switch_track_off.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--<size-->
<!--android:width="60dp"-->
<!--android:height="35dp">-->
<!--</size>-->
<solid
android:color="@android:color/darker_gray">
</solid>
<corners android:radius="2dip" />
</shape>
3):然后定义drawable文件:switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/switch_track_on"></item>
<item
android:state_checked="false"
android:drawable="@drawable/switch_track_off"></item>
</selector>
最后在布局文件
<Switch
android:id="@+id/switch_autoupdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_track"/>