这是我参与 8 月更文挑战的第 30 天,活动详情查看: 8月更文挑战
背景
在项目中常常有开关控件的需求, 系统提供的默认开关有时并不能满足所有需求, 比如颜色, 形状等, 这个时候就需要对控件进行改造, 以适应需求. 本篇就简单介绍
Switch
控件的基本使用
使用
在xml中插入控件
<Switch
android:id="@+id/sw_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:track="@drawable/track"
android:thumb="@drawable/thumb"/>
关闭状态设置灰色底图
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 高度30 此处设置宽度无效-->
<size android:height="30dp"/>
<!-- 圆角弧度 25 -->
<corners android:radius="25dp"/>
<!-- 变化率 定义从左到右的颜色不变 -->
<gradient
android:endColor="#666666"
android:startColor="#666666" />
</shape>
打开状态设置为蓝色底图
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 高度40 -->
<size android:height="40dp"/>
<!-- 圆角弧度 25 -->
<corners android:radius="25dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#0000FF"
android:startColor="#0000FF" />
</shape>
关闭状态设置为白色滑块, 并在外层添加灰色边框
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 高度40 -->
<size android:height="40dp" android:width="40dp"/>
<!-- 圆角弧度 20 -->
<corners android:radius="25dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#ffffff"
android:startColor="#ffffff" />
<stroke android:width="1dp"
android:color="#9e9e9e"/>
</shape>
关闭状态设置为白色滑块, 并在外层添加蓝色边框
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 高度40 -->
<size android:height="40dp" android:width="40dp"/>
<!-- 圆角弧度 25 -->
<corners android:radius="25dp"/>
<!-- 变化率 -->
<gradient
android:endColor="#ffffff"
android:startColor="#ffffff" />
<stroke android:width="1dp"
android:color="#0000FF"/>
</shape>
使用选择器设置底色
<?xml version="1.0" encoding="utf-8"?>
<!-- 控制Switch在不同状态下,底下下滑条的颜色 -->
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:drawable="@drawable/blue_track" />
<item android:drawable="@drawable/gray_track" />
</selector>
使用选择器控制滑块
<?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/blue_thumb" />
<item android:drawable="@drawable/gray_thumb" />
</selector>
监听开关状态
Switch mSwitch = findViewById(R.id.sw_switch);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
常用属性
android:checked
设置控件是否被选中
android:track
设置底色
android:thumb
设置滑块
android:text
设置控件文字
android:textOn
设置选中时滑块上的文字
android:textOff
设置未选中时滑块上的文字
android:showText
设置滑块是否显示文字(如果设置了textOn
和textOff
,那么showText
必须为true文字才能显示)