I've been trying to set a gradient background in a Material Button from Material Components for Android, but it's not working. So, how to set a gradient background in a Material Button?
Material Button is a customizable button component with updated visual styles. This button component has several built-in styles to support different levels of emphasis, as typically any UI will contain a few different buttons to indicate different actions.
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
.
backgroundTint
is still the default MaterialButton style.android:background
, you have to make sure to null out backgroundTint
(either app:backgroundTint="@null"
or app:backgroundTint="@empty"
), to avoid that the custom background doesn't get tinted.android:background
the default MaterialShapeDrawable
is not used. Some features like stroke, shapeappearance, ripple are not set (since they are related to the MaterialShapeDrawable
) . You have to provide them with your custom background.I found this solution.
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_gradient_example"
app:backgroundTint="@null" />
selector_gradient_example
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/banana_yellow">
<item android:state_enabled="true">
<ripple android:color="@color/banana_yellow">
<item>
<shape android:shape="rectangle">
<gradient android:angle="135" android:endColor="@color/banana_yellow" android:startColor="@color/main_yellow" />
</shape>
</item>
</ripple>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<gradient android:angle="315" android:endColor="#ede0be" android:startColor="#e0bf7e" />
</shape>
</item>
</selector>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With