如何更改主题中的材质按钮禁用状态背景颜色?

Ser*_*rov 8 android android-button material-design material-components material-components-android

我在我的 android 项目中使用材料设计组件。

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

我想在我的主题中更改DISABLED颜色,但我不知道如何做到这一点。

我尝试查看Widget.MaterialComponents.Button样式,发现它具有"backgroundTint"属性:

<item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>
Run Code Online (Sandbox Code Playgroud)

但它没有禁用状态样式,见下文:

<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>
Run Code Online (Sandbox Code Playgroud)

我总是可以自己添加它,但是禁用按钮的初始灰色来自哪里?

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

PS我正在使用Theme.MaterialComponents.NoActionBar主题。

谢谢!

Gab*_*tti 13

禁用状态使用的颜色是选择器中的最后一行:

<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 在此处输入图片说明

全局更改只需使用materialButtonStyle应用主题中的属性。

<style name="AppTheme" parent="Theme.MaterialComponents.*">
  <item name="materialButtonStyle">@style/My.Button</item>
</style>
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据自己的喜好自定义样式。

<style name="My.Button" parent="@style/Widget.MaterialComponents.Button">
 <item name="backgroundTint">@color/my_color_selector</item>
 ...
</style>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

然后在您的布局中添加没有样式的按钮。它将使用由样式全局定义的My.Button样式。

<com.google.android.material.button.MaterialButton
  .../>
Run Code Online (Sandbox Code Playgroud)


Muk*_*osh 6

1.创建文件夹res/color。2.创建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>
Run Code Online (Sandbox Code Playgroud)

3.在styles.xml中创建一个样式,其父级为 Widget.MaterialComponents.Button 。

<style name="MaterialButtonStyle" parent="Widget.MaterialComponents.Button.UnelevatedButton">
        <item name="backgroundTint">@color/color_states_materialbutton</item>
</style>
Run Code Online (Sandbox Code Playgroud)

4.在布局中的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"/>
Run Code Online (Sandbox Code Playgroud)