Search code examples
androidandroid-buttonmaterial-components-androidmaterial-components

How do I programmatically change the style of a Material Component Text Button in Android?


I have a material text button <Button android:id="@+id/button" style="@style/Widget.MaterialComponents.Button.TextButton"/> that I'd like to change the colour of at runtime. So I set the text colour using button.setTextColor(Color.rgb(10, 10, 10)). Unfortunately, this doesn't change the background drawable, so when I click on the button it's ripple colour is unchanged. I'm guessing I need to change the background with something like attackButton.background = getDrawable(R.drawable.ripple), but I'm not sure how to populate the ripple.xml. Does this method make sense for changing the button text colour and ripple? If so, how should I write the ripple.xml?


Solution

  • To change the colors in the MaterialButton you can use:

    • button.setBackgroundTintList to change the background tint. You should use a selector.
    • button.setRippleColor to change the ripple color. Also in this case you should use a selector (see below)
    • button.setTextColor to change the color of the text. Also in this case you should use a selector.

    It is the default selector used in the ripple color:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
      <item android:alpha="@dimen/mtrl_low_ripple_pressed_alpha" android:color="?attr/colorPrimary" android:state_pressed="true"/>
      <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true" android:state_hovered="true"/>
      <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true"/>
      <item android:alpha="@dimen/mtrl_low_ripple_hovered_alpha" android:color="?attr/colorPrimary" android:state_hovered="true"/>
      <item android:alpha="@dimen/mtrl_low_ripple_default_alpha" android:color="?attr/colorPrimary"/>
    
    </selector>