前言
讲解基本Switch的使用与记录一些开发点子
转载请注明来源:https://www.cnblogs.com/guanxinjing/p/16313742.html
基本属性
- android:showText:设置on/off的时候是否显示文字,boolean
- android:splitTrack:是否设置一个间隙,让滑块与底部图片分隔,boolean
- android:switchMinWidth:设置开关的最小宽度
- android:switchPadding:设置滑块内文字的间隔
- android:switchTextAppearance:设置开关的文字外观,暂时没发现有什么用...
- android:textOff:按钮没有被选中时显示的文字
- android:textOn:按钮被选中时显示的文字
- android:textStyle:文字风格,粗体,斜体写划线那些
- android:track:底部的图片
- android:thumb:滑块的图片
设置状态监听
mBinding.timeFormatSwitch.setOnCheckedChangeListener { switchView, isChecked ->
if (switchView.isPressed){
}
}
自定义Switch
效果图
背景xml
要做到滑块thumb大于背景的关键是android:top 与 android:bottom(注意是item里的属性)这里的属性类似于 android:layout_marginTop
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<layer-list>
<item android:top="3dp"
android:bottom="3dp">
<shape
android:shape="rectangle">
<corners android:radius="10dp"/>
<gradient
android:type="linear"
android:angle="0"
android:startColor="#48F3D0"
android:endColor="#1DBBFF"/>
</shape>
</item>
</layer-list>
</item>
<item android:state_checked="false">
<layer-list>
<item android:top="3dp"
android:bottom="3dp">
<shape
android:shape="rectangle">
<corners android:radius="10dp"/>
<solid android:color="#646464"/>
</shape>
</item>
</layer-list>
</item>
</selector>
滑块xml
<?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"/>
<solid android:color="#ffffff"/>
</shape>
在view里设置它们
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/timeFormatSwitch"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_marginEnd="35dp"
app:track="@drawable/settings_selector_shape_rectangle_48f3d0_10dp"
android:thumb="@drawable/settings_shape_oval_ffffff_30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
End
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/16313742.html
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
来源:https://www.cnblogs.com/guanxinjing/p/16313742.html |