如何解决更改 MaterialButtonToggleGroup 的背景颜色
我正在使用 MaterialButtonToggleGroup 创建选择器按钮。 我想更改 MaterialButton 按钮的背景颜色。它的默认颜色是浅蓝色,我想把它改成浅绿色。目前,我正在使用可绘制扇区来更改背景颜色,但它不起作用。
默认颜色,
这是我的布局,
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:checkedButton="@id/btnOutline"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:visibility="visible"
app:layout_constraintRight_toRightOf="parent"
app:singleSelection="true">
<com.google.android.material.button.MaterialButton
android:id="@+id/btnOutline"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_selector"
android:text="@string/outline"
android:textAllCaps="false" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnMain"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:background="@drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main"
android:textAllCaps="false" />
</com.google.android.material.button.MaterialButtonToggleGroup>
这是我的可绘制文件“button_selector”,
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/selector_color"/>
</selector>
这是“selector_color”文件,
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#93cdcb"/>
</shape>
解决方法
对于材质按钮,您应该使用 app:backgroundTint 而不是 android:background Android 文档在这里也提到了它: Locator Strategies
不要使用 android:background 属性。 MaterialButton 管理 它自己的背景可绘制,并设置一个新的背景意味着 MaterialButton 不能再保证它的新属性 介绍将正常运行
对于填充按钮,这个类使用你的主题的 ?attr/colorPrimary 用于背景色调颜色和 ?attr/colorOnPrimary 用于文本 颜色。对于未填充的按钮,此类使用 ?attr/colorPrimary 文本颜色和背景色调的透明。
,您可以尝试在“android:backgroundTint”属性上设置选择器,而不是将其设置为“android:background”。如果您想更新边框颜色,请考虑更新和 'app:strokeColor'
,MaterialButton 的背景颜色由 backgroundTint 属性定义。
默认值为:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?attr/colorPrimary" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
您可以在 xml 布局中更改它,也可以定义自定义样式:
<com.google.android.material.button.MaterialButton
style="@style/ButtonStyle"
.. />
与:
<style name="ButtonStyle" parent="Widget.MaterialComponents.Button">
<item name="backgroundTint">@color/your_button_background_selector</item>
...
</style>
,
我遇到了同样的问题,并通过在选择器中使用 android:state_checked="true"
而不是 android:state_selected="true"
解决了它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。