开篇之前先普及下Switch的一些常用的属性,便于我们对这些属性做自定义扩展
常用属性:
android:typeface="normal":设置字体类型
android:track="":设置开关的轨迹图片
android:textOff="开":设置开关checked的文字
android:textOn="关":设置开关关闭时的文字
android:thumb="":设置开关的图片
android:switchMinWidth="":开关最小宽度
android:switchPadding="":设置开关 与文字的空白距离
android:switchTextAppearance="":设置文本的风格
android:checked="":设置初始选中状态
android:splitTrack="true":是否设置一个间隙,让滑块与底部图片分隔(API 21及以上)
android:showText="true":设置是否显示开关上的文字(API 21及以上)
系统给我们提供的Switch开关样式跟颜色都是固定不可设置的,在不同的业务场景下可能我们需要去改变这些属性,定制与我们开发项目相吻合的个性化样式,那本篇博客将为大家分享如果修改Switch的样式。
效果图:
如图所示,上面的Switch是系统默认的样式,下面的黄色背景的是修改过样式的Switch,通过修改Switch的thumb和track即可修改成自己想要的样式。
1.首先定义一个shape文件,命名为shape_switch_thumb.xml,即为Switch开的的边缘指示部分
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="30dp"
android:height="30dp"></size>
<solid android:color="@android:color/white"></solid>
</shape>
2.然后定义一个selector文件,命名为selector_switch_track.xml,定义Switch打开跟关闭的选中状态
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_switch_track_on" android:state_checked="true" />
<item android:drawable="@drawable/shape_switch_track_off" android:state_checked="false" />
</selector>
对应的shape_switch_track_on和shape_switch_track_off文件如下:
2.<1>. shape_switch_track_on.xml,Switch的选中状态:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ccd61f"></solid>
<corners android:radius="32dp"></corners>
</shape>
2.<2>.shape_switch_track_off.xml,Switch未选的状态(正常状态):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="@android:color/darker_gray">
</solid>
<corners
android:radius="30dp">
</corners>
</shape>
3.应用到布局文件中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.zhuandian.swtichdemo.MainActivity">
<Switch
android:layout_marginBottom="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
/>
<Switch
android:track="@drawable/selector_switch_track"
android:thumb="@drawable/shape_switch_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
/>
</LinearLayout>