我在我的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"/>


android - 如何更改主题中的 Material 按钮禁用状态背景颜色?-LMLPHP
android - 如何更改主题中的 Material 按钮禁用状态背景颜色?-LMLPHP

要进行全局更改,只需在应用程序主题中使用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
  .../>

08-18 18:03
查看更多