切换按钮组 (Toggle Button Group)
切换按钮组(也称为分段按钮)用于在多个互斥或并列的选项之间进行选择。

代码实现
通过 MaterialButtonToggleGroup 容器管理一组 MaterialButton。
xml
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true"
app:selectionRequired="true">
<Button
android:id="@+id/btn_left"
style="?attr/materialButtonOutlinedStyle"
android:text="左对齐" />
<Button
android:id="@+id/btn_center"
style="?attr/materialButtonOutlinedStyle"
android:text="居中" />
<Button
android:id="@+id/btn_right"
style="?attr/materialButtonOutlinedStyle"
android:text="右对齐" />
</com.google.android.material.button.MaterialButtonToggleGroup>kotlin
// 监听选中变化
toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
if (isChecked) {
// 执行对应逻辑
}
}
// 运行时选中
toggleGroup.check(R.id.btn_center)核心属性
| 属性 | 描述 | 默认值 |
|---|---|---|
app:singleSelection | 是否为单选模式 | false |
app:selectionRequired | 是否强制必须选一个(不能全取消) | false |
android:spacing | 按钮之间的间距 | 0dp |
样式提示
样式推荐
通常建议使用 ?attr/materialButtonOutlinedStyle 作为切换组子项的样式,这样能获得更清晰的分段视觉边界。