如何在我的主题中更改 material 按钮禁用状态背景颜色?

How to change material button disabled state background color in my theme?

我在 android 项目中使用 Material 设计组件。

我的问题是我无法更改 DISABLED material 按钮 (https://material.io/develop/android/components/material-button/) 的背景颜色。

我想更改主题中的 DISABLED 颜色,但我不知道该怎么做。

我试着查看 Widget.MaterialComponents.Button 风格,我发现它有 "backgroundTint" 属性:

<item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>

但是没有disabled状态样式,见下:

<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 按钮的初始灰色是从哪里来的?

在我的主题中全局更改此颜色的最佳方法是什么?

P.S。我正在使用 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>

然后在您的布局中添加 Button without 样式。它将使用 My.Button 样式全局定义的样式。

<com.google.android.material.button.MaterialButton
  .../>

1.Create 文件夹 res/color。 2.Create xml 喜欢 color.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false"
        android:color="@color/colorDisabled"  />
    <item android:color="@color/colorEnabled" />
</selector>

3.Create styles.xml 中的样式,父级 Widget.MaterialComponents.Button .

<style name="MaterialButtonStyle" parent="Widget.MaterialComponents.Button.UnelevatedButton">
        <item name="backgroundTint">@color/color_states_materialbutton</item>
</style>

4.Set 布局中 MaterialButton 的样式:

<com.google.android.material.button.MaterialButton
    style="@style/MaterialButtonStyle"
    android:id="@+id/disabled_material_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="@string/button_label_disabled"/>