我在我的android项目中使用Material设计组件。
我的问题是我无法更改材质按钮的禁用背景颜色(https://material.io/develop/android/components/material-button/)。
我想更改主题中的“禁用”颜色,但是我不知道该怎么做。
我尝试查看Widget.MaterialComponents.Button
样式,发现它具有"backgroundTint"
属性:
<item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>
但是它没有禁用状态样式,请参见下文:
<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>
我总是可以自己添加它,但是DISABLED按钮的最初呈灰色的颜色从何而来?
在我的主题中全局更改此颜色的最佳方法是什么?
附言我正在使用
Theme.MaterialComponents.NoActionBar
主题。谢谢!
最佳答案
禁用状态使用的颜色是选择器中的最后一行:
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
要进行全局更改,只需在应用程序主题中使用
materialButtonStyle
属性。<style name="AppTheme" parent="Theme.MaterialComponents.*">
<item name="materialButtonStyle">@style/My.Button</item>
</style>
然后,您可以根据需要自定义样式。
<style name="My.Button" parent="@style/Widget.MaterialComponents.Button">
<item name="backgroundTint">@color/my_color_selector</item>
...
</style>
或新的
materialThemeOverlay
属性以覆盖颜色(它需要库的版本1.1.0):<style name="My.Button" parent="@style/Widget.MaterialComponents.Button">
<item name="materialThemeOverlay">@style/MyButtonThemeOverlay</item>
...
</style>
<style name="MyButtonThemeOverlay">
<item name="colorOnSurface">@color/mycolor</item>
</style>
然后在布局中添加不带样式的按钮。它将使用由
My.Button
样式全局定义的样式。<com.google.android.material.button.MaterialButton
.../>