材料设计按钮背景渐变

10

我能否通过谷歌材料库为MaterialButton设置渐变颜色?app:backgroundTint只能设置颜色而无法设置渐变颜色。

4个回答

5

MaterialButton在发布 1.2.0-alpha06 前会忽略 android:background 属性。

从这个版本开始,您可以使用以下代码:

<Button
    android:background="@drawable/bg_button_gradient"
    app:backgroundTint="@null"
    ... />

如果您需要在较早版本的库中使用此功能,可以使用 AppCompatButton。类似这样:
<androidx.appcompat.widget.AppCompatButton
    android:background="@drawable/bg_button_gradient"

3

不确定但根据developer.android.com,我们甚至不能添加android:background,似乎无法向materialButton添加drawable


1
无法使用默认方法完成此操作。最好使用渐变可绘制对象。
创建一个新的xml文件并将其放入drawable中,然后将其作为背景添加到按钮中。

gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
   <gradient
      android:startColor="#000000"
      android:centerColor="#ffffff"
      android:endColor="#cfcfcf"
      android:angle="270" />
</shape>

layout.xml

 <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient"
    android:text="YourText" >

2
我知道如何做。我想知道的是是否可以在谷歌的Material组件库中的MaterialButton上完成它。 - Melvin Kent
没有默认的方法来做这个。 - Anisuzzaman Babla

-2
创建可绘制文件,例如。
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:angle="135"
    android:centerColor="#6200ee"
    android:endColor="#6200ee"
    android:startColor="#3700b3"
    android:type="linear" />
 </shape>

并将此文件设置为按钮的背景


3
可以在MaterialButton上实现吗? - Melvin Kent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接