How to set a gradient background to a Material Button?

帅比萌擦擦* 提交于 2019-12-12 14:32:21

问题


I'm currently using this code but the background is not changing.It is still showing accent-color as background.

<com.google.android.material.button.MaterialButton
    android:id="@+id/materialButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello"
    app:cornerRadius="32dp"
    android:background="@drawable/gradiant_blue"/>

gradiant_blue.xml

<shape
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

   <gradient
       android:angle="-45"
       android:startColor="#2979FF"
       android:endColor="#7C4DFF"/>
</shape>

I'm currently using

Material Components version : 1.0.0-rc02


回答1:


LE: From my point of view I suggest you use Button or AppCompatButton.

Try this:

gradient.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="#027FEE"
        android:startColor="#2CC6F2" />
</shape>

button.xml

<!-- replace MaterialButton with Button or AppCompatButton -->
<com.google.android.material.button.MaterialButton
    android:id="@+id/materialButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient"
    android:text="Hello" />

Result:

With corner radius change gradient.xml to:

<?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="#027FEE"
        android:startColor="#2CC6F2" />
    <corners android:radius="32dp"/>
</shape>

Result:




回答2:


Please read the documentation for Material button, from here

It says, "For filled buttons, your theme’s colorPrimary provides the default background color of the component, and the text color is colorOnPrimary. For unfilled buttons, your theme’s colorPrimaryprovides the default text color of the component, and the background color is transparent by default."

I think that's the reason you are seeing some other color(accent-color) also please check the attributes that set background colour.

Following attributes are mentioned :

app:backgroundTint

app:backgroundTintMode




回答3:


To set background you need to make your base theme extend

Theme.AppCompat.Light.NoActionBar

and not

Theme.MaterialComponents.Light.NoActionBar



来源:https://stackoverflow.com/questions/52371234/how-to-set-a-gradient-background-to-a-material-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!