Switch是在4.0以后推出的,要注意开发时的minsdk设置,google在API 21后也推出support v7 包下的SwitchCompa的Material Design
效果图
布局
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20sp"
>
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switchCompat"
android:text="按钮1"
android:checked="false"
app:showText="true"
android:textOn="开"
android:textOff="关"
app:switchPadding="20dp"
app:switchTextAppearance="@style/ontextoff"
app:theme="@style/scstyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.appcompat.widget.SwitchCompat
android:layout_marginLeft="20sp"
android:text="按钮2"
android:checked="true"
app:showText="true"
android:textOn="开"
android:textOff="关"
app:switchPadding="20dp"
app:switchTextAppearance="@style/ontextoff"
app:theme="@style/scstyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
- @style
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--文字颜色和大小-->
<style name="ontextoff" parent="Theme.AppCompat.Light">
<item name="android:textColor">#0d09f1</item>
<item name="android:textSize">8sp</item>
</style>
<style name="scstyle" parent="Theme.AppCompat.Light">
<!--开启时的颜色-->
<item name="colorControlActivated">#00e6db</item>
<!--关闭时的颜色-->
<item name="colorSwitchThumbNormal">#FFFFFF</item>
<!--关闭时的轨迹颜色-->
<!-- <item name="android:colorForeground">#ecd502</item>-->
</style>
</resources>
- 代码设置轨道和按钮
switchCompat.setTrackResource(R.mipmap.ic_launcher);//轨道 自定义图片
switchCompat.setThumbResource(R.mipmap.ic_launcher);//按钮 自定义图片
- 点击的处理
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
Log.i("TAG","开的点击处理--------");
}else {
Log.i("TAG","关的点击处理--------");
}
}
});
属性
- 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及以上)