开关 (Switch)
源:Switch
开关用于切换单个设置的状态。它是二进制选择,如开启/关闭、是/否。

核心结构 (Anatomy)

- 轨道 (Track) | 2. 滑块 (Handle/Thumb) | 3. 图标 (Icon)
代码实现
注意事项
MaterialSwitch 继承自 SwitchCompat,它不会像普通 CheckBox 那样被自动填充,必须在 XML 中显式指定完整类名。
xml
<com.google.android.material.materialswitch.MaterialSwitch
android:id="@+id/materialSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开启通知"
app:thumbIcon="@drawable/ic_check" />kotlin
materialSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
// 响应开关切换
}核心属性
| 属性 | 描述 | 默认值 |
|---|---|---|
app:thumbIcon | 滑块中间显示的图标 | null |
app:thumbTint | 滑块着色 | ?attr/colorOnPrimary (选中) |
app:trackTint | 轨道着色 | ?attr/colorPrimary (选中) |
主题化
M3 开关在未选中状态下通常有一个深色的轮廓(Track Decoration),选中后消失。
xml
<style name="Widget.App.Switch" parent="Widget.Material3.CompoundButton.MaterialSwitch">
<item name="materialThemeOverlay">@style/ThemeOverlay.App.Switch</item>
</style>