Search code examples
androidandroid-buttonandroid-themeandroid-stylesmaterial-components-android

Apply Style to MaterialButton programmatically


I'm trying to create a custom view extending from MaterialButton and apply style in code so I don't need to do it in xml.

class CustomRedButton @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyleAttr: Int = 0
) : MaterialButton(ContextThemeWrapper(context, R.style.ButtonRedStyle), attrs, defStyleAttr) 

Style is:

<style name="ButtonRedStyle" 
    parent="Widget.MaterialComponents.Button.TextButton">
    <item name="backgroundTint">@color/red</item>
    <item name="rippleColor">@color/grey</item>
    <item name="strokeWidth">1dp</item>
    <item name="strokeColor">@color/black</item>
</style>

Everything works fine but backgroundTint property. For some reason background color is not changing, and it has Theme's primary color. However, if I try to apply the style to a MaterialButton in xml it does change the color.

Any idea why that can be happening or how I can achieve it?


Solution

  • I'm also facing the same issue. The only workaround I've found so far is to set the tint programmatically like:

    button.setBackgroundTintList(ColorStateList.valueOf(Color.RED));