MaterialButtonToggleGroup选中MaterialButton背景Drawable修改方法
核心问题成因
Material组件库中的MaterialButton会优先使用组件内置的backgroundTint状态着色逻辑渲染背景,直接在布局中给按钮设置android:background会被默认的着色器逻辑覆盖;搭配materialButtonOutlinedStyle默认样式时,自定义的选中态Drawable、圆角配置很容易被默认样式重置,最终达不到预期效果。
可直接落地的实现步骤
- 为组内按钮编写专属自定义样式,替换默认的outlined按钮主题,核心是关闭默认的自动着色逻辑:
<style name="ToggleButton.CustomStyle" parent="Widget.MaterialComponents.Button.OutlinedButton"> <!-- 关闭默认背景着色,避免覆盖自定义Drawable --> <item name="backgroundTint">@null</item> <!-- 绑定自定义的状态背景 --> <item name="android:background">@drawable/bg_toggle_button_state</item> <!-- 沿用之前定义的圆角形状配置 --> <item name="shapeAppearance">@style/ToggleButton.Rounded</item> <!-- 适配状态的文字颜色,避免选中态和背景对比度不足 --> <item name="android:textColor">@color/selector_toggle_text</item> </style> - 编写选中/未选中态的状态背景Drawable,放在
res/drawable/bg_toggle_button_state.xml中:<selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中态配置 --> <item android:state_checked="true"> <shape android:shape="rectangle"> <solid android:color="@color/colorPrimary"/> <corners android:radius="16dp"/> </shape> </item> <!-- 未选中态配置 --> <item android:state_checked="false"> <shape android:shape="rectangle"> <solid android:color="@android:color/transparent"/> <stroke android:width="1dp" android:color="@color/colorOutline"/> <corners android:radius="16dp"/> </shape> </item> </selector> - 调整布局内的按钮样式引用,替换之前直接引用的默认outlined样式:
<com.google.android.material.button.MaterialButtonToggleGroup android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" app:singleSelection="true" app:selectionRequired="true" app:checkedButton="@+id/toggleButtonFolder"> <com.google.android.material.button.MaterialButton android:id="@+id/toggleButtonFolder" style="@style/ToggleButton.CustomStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Folders" /> <com.google.android.material.button.MaterialButton android:id="@+id/toggleButtonRecent" style="@style/ToggleButton.CustomStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Recent" /> </com.google.android.material.button.MaterialButtonToggleGroup>
常见踩坑提醒
- 不要把状态背景绑定到
MaterialButtonToggleGroup父容器上,每个子按钮的选中状态是独立的,状态选择器必须直接绑定到每个子按钮的属性上 - 使用Material库1.7.0及以上版本时,必须显式配置
backgroundTint="@null",组件默认会为outlined类型的按钮绑定内置的状态色值,哪怕设置了自定义背景也会被内置着色逻辑渲染成默认效果 - 形状配置不要重复设置:如果已经在状态Drawable的shape标签里写了圆角半径,就不要再给按钮配置
app:shapeAppearance的圆角参数,避免两层渲染导致的圆角显示异常 - 如果仅需要调整选中态的填充色,不需要自定义描边效果,可以直接给按钮设置
app:backgroundTint为颜色状态选择器,无需额外编写自定义Drawable
内容的提问来源于stack exchange,提问作者Himanshu Malik
相关产品推荐
相关产品推荐

