老规矩先上图

引入
implementation 'com.google.android.material:material:1.4.0'
说明
该控件就是Switch控件的增强版本,属性基本一致
属性
| 属性 | 描述 |
|---|---|
| android:text | 文本 |
| android:textOn | 滑块打开时显示的文本 |
| android:textOff | 滑块关闭时显示的文本 |
| android:thumb | 滑块图片 |
| app:track | 轨迹图片 |
| app:switchMinWidth | 滑块开关的最小长度 |
| app:switchPadding | 滑块开关与文本的间距 |
| android:checked | 是否选中 |
| app:splitTrack | 是否将滑块与轨迹分开 |
| app:showText | 是否显示textOn/textOff 文本 |
| app:thumbTint | 设置滑块颜色 |
| app:trackTint | 设置轨迹颜色 |
| app:thumbTintMode | 用于应用滑动按钮色调的混合模式 |
注意
设置textOn/textOff 时一定要设置showText=“true”,否则没有效果
源代码
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.switchmaterial.SwitchMaterial
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开关"
android:textOff="关"
android:textOn="开"
android:checked="true"
app:showText="true"
app:splitTrack="true"
app:switchPadding="5dp"
app:thumbTint="@color/black"
app:trackTint="@color/design_default_color_error"/>
androidx.coordinatorlayout.widget.CoordinatorLayout>