Search code examples
androidmaterial-designandroid-buttonmaterial-componentsmaterial-components-android

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


I am using Material design components in my android project.

My promblem is that i cannot change DISABLED background color of the material button (https://material.io/develop/android/components/material-button/).

I want to change DISABLED color in my theme, but i cannot figure out how to do this.

I tried looking at Widget.MaterialComponents.Button style and I found out that it has "backgroundTint" property:

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

But it does not have disabled state style, see below:

<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>

I can always add it myself, but where does initial greyed out color of a DISABLED button come from?

What is the best way to change this color globally in my theme?

P.S. I am using Theme.MaterialComponents.NoActionBar theme.

Thanks!


Solution

  • The color used by disable state is the last line in the selector:

    <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
    

    enter image description here enter image description here

    To change globally just use the materialButtonStyle attribute in your app theme.

    <style name="AppTheme" parent="Theme.MaterialComponents.*">
      <item name="materialButtonStyle">@style/My.Button</item>
    </style>
    

    Then you can customize your style as you prefer.

    <style name="My.Button" parent="@style/Widget.MaterialComponents.Button">
     <item name="backgroundTint">@color/my_color_selector</item>
     ...
    </style>
    

    or the new materialThemeOverlay attribute to override the colors (it requires the version 1.1.0 of the library):

    <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>
    

    Then in your layout just add the Button without style. It will use the style defined globally by the My.Button style.

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