How to set a gradient background in a Material Button from Material Components?
Starting with the version 1.2.0-alpha06
you can use the android:background
attribute in the MaterialButton
.
<MaterialButton
app:backgroundTint="@null"
android:background="@drawable/button_gradient"
... />
Otherwise if you can't use the 1.2.0-alpha06 or higher you have to use the AppCompatButton
component.
Just a some tips about the MaterialButton
.
- Currently the
backgroundTint
is still the default MaterialButton style.
If you are using a customandroid:background
, you have to make sure to null outbackgroundTint
(eitherapp:backgroundTint="@null"
orapp:backgroundTint="@empty"
), to avoid that the custom background doesn't get tinted. - using a custom
android:background
the defaultMaterialShapeDrawable
is not used. Some features like stroke, shapeappearance, ripple are not set (since they are related to theMaterialShapeDrawable
) . You have to provide them with your custom background.
From the documentation for MaterialButton
:
Do not use the
android:background
attribute. MaterialButton manages its own background drawable, and setting a new background meansMaterialButton
can no longer guarantee that the new attributes it introduces will function properly. If the default background is changed,MaterialButton
cannot guarantee well-defined behavior.
The only supported way to modify the background of the button is to set a color value to the app:backgroundTint
attribute. Unfortunately, gradients are not supported here either; you can only use a simple color value or a ColorStateList
.
So, there is no supported way to use a gradient background with MaterialButton.