Search code examples
androidandroid-buttonandroid-stylesmaterial-components-androidmaterial-components

Gradient color using MaterialButton and shapeAppearance


I want to make a Button like this one : enter image description here

I try it using style with shapeAppearance :

<style name="ShapeAppearance.Button" parent="ShapeAppearance.MaterialComponents">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopLeft">@dimen/button_corner_radius</item>
    <item name="cornerSizeTopRight">5dp</item>
    <item name="cornerSizeBottomRight">@dimen/button_corner_radius</item>
    <item name="cornerSizeBottomLeft">5dp</item>
</style>

<dimen name="button_corner_radius">40dp</dimen>

I apply the style in my MaterialButton like this :

app:shapeAppearance="@style/ShapeAppearance.Button" 

The result is :

enter image description here

Now, I try to put a linear gradient :

  • #DF2D48 @ 0.0
  • #D72D46 @ 0.2
  • #AF223B @ 0.5
  • #AC2139 @ 1.0

For example :

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#DF2D48"
        android:centerColor="#D72D46"
        android:endColor="#AC2139"
        android:angle="360" />
</shape>

and I apply it using in my Shape style :

<item name="android:background">@drawable/test</item>

But the result is the same. Why ?


Solution

  • Gradient color using Material Button:

    Gradient MaterialButton

    MaterialButton : To use a custom drawable background with the MaterialButton background tint attribute should be null ref code: app:backgroundTint="@null"

     <com.google.android.material.button.MaterialButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:focusable="true"
                    android:text="@string/button_enabled"
    
                    app:backgroundTint="@null"
                    android:background="@drawable/gradient_1"
                   />
    

    Gradient with shape: res/drawable/gradient_1.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="0"
            android:endColor="#DD8E54E9"
            android:startColor="#CC225AE0" />
            <corners android:topLeftRadius="18dp"
                android:bottomRightRadius="18dp"
                android:topRightRadius="5dp"
                android:bottomLeftRadius="5dp"
                />
            <stroke
                android:width="6dp"
                android:color="#007879E8" />
    </shape>