1

Hello Learned Friends,

I am using Material Design Theme but I need to overried its statePressed so that when the button is clicked it changes color (highlighted for a moment) as demonstrated below.

enter image description here

For this I have a drawable which I set on the buttons as follows

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="false">
    <shape>
        <solid android:color="@color/primaryColor" />
        <stroke android:color="@color/primaryDarkColor" android:width="@dimen/stroke_width"/>
        <corners android:radius="@dimen/corner_radius" />

    </shape>

</item>


<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/secondaryColor" />
        <stroke android:color="@color/secondaryLightColor" android:width="@dimen/stroke_width" />
        <corners android:radius="@dimen/corner_radius" />

    </shape>

</item>

I also got a ThemeOverlay to override the state pressed

    <style name="ThemeOverlay.Red.UnitedStates" parent="">
<item name="android:colorPressedHighlight">@color/secondaryColor</item>
    </style>

Unfortunately when I click the buttons the highlight doesn't happen.

What could I be missing?

This is Material Theme XML

 <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryVariant">@color/primaryLightColor</item>
    <item name="colorPrimaryDark">@color/primaryDarkColor</item>
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Tonnie
  • 4,865
  • 3
  • 34
  • 50
  • How are you applying the drawable to the buttons? As background drawable? Also, how are you attaching your ThemeOverlay to your App Theme? Note: Your selector code doesn't seem to be right, the default state (not pressed) should always be at the bottom. So you should put state_pressed before default. check this link: https://stackoverflow.com/questions/14023886/android-button-selector – nulldroid May 12 '21 at 17:48

1 Answers1

2

You can use just the app:backgroundTint attribute:

     <com.google.android.material.button.MaterialButton
          app:backgroundTint="@color/custom_button_selector"
          ../>

with:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/red600" android:state_pressed="true"/>
    <item android:color="?attr/colorPrimary" android:state_enabled="true"/>
    <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>

Normal state:

enter image description here

Pressed state:

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841