如何为材质按钮设置渐变背景?

时间:2018-09-17 15:31:58

标签: android android-drawable android-button material-components-android

我当前正在使用此代码,但是背景没有改变。它仍显示着强调色作为背景。

<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>

我当前正在使用

  

材料组件版本:1.0.0-rc02

4 个答案:

答案 0 :(得分:8)

要将自定义可绘制背景与MaterialButton一起使用,可以使用android:background属性:

<MaterialButton
    app:backgroundTint="@null"
    android:background="@drawable/bkg_button_gradient"
    ... />

注意::它至少需要 1.2.0-alpha06

版本

当前,添加 app:backgroundTint="@null" 非常重要,以避免默认情况下自定义背景不会被着色为backgroundTint

对于较低版本的Material Components Library,您必须使用 AppCompatButton

答案 1 :(得分:1)

LE:从我的角度来看,我建议您使用ButtonAppCompatButton

尝试一下:

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

使用corner radius 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" />
    <corners android:radius="32dp"/>
</shape>

结果:

result

答案 2 :(得分:0)

请阅读here

中“材质”按钮的文档

它说, “对于填充按钮,主题的colorPrimary提供组件的默认背景颜色,文本颜色为colorOnPrimary。对于未填充按钮,主题的colorPrimary提供组件的默认文本颜色,背景颜色默认为透明。” / p>

我认为这就是您看到其他颜色(强调颜色)的原因,也请检查设置背景颜色的属性。

提到以下属性:

app:backgroundTint

app:backgroundTintMode

答案 3 :(得分:0)

要设置背景,您需要扩展基本主题

  

Theme.AppCompat.Light.NoActionBar

而不是

  

Theme.MaterialComponents.Light.NoActionBar