Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a gradient background in a Material Button from Material Components?

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?

like image 823
GianMS Avatar asked Oct 20 '18 17:10

GianMS


People also ask

What is material button in Android Studio?

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.


2 Answers

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 custom 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.
  • using a custom 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.
like image 72
Gabriele Mariotti Avatar answered Nov 07 '22 23:11

Gabriele Mariotti


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>
like image 22
Иван Кононенко Avatar answered Nov 07 '22 22:11

Иван Кононенко