android:背景在 material 设计按钮组件中不起作用

android: background is not working in the material design button component

我想在我用 Kotlin 开发的 Android 应用程序中制作一个渐变按钮。我已经为渐变背景制作了可绘制文件,但是当我为按钮提供自定义背景时,它不起作用,没有任何变化。这是渐变背景的代码,下面是按钮的 XML 代码。

    <item>
        <shape android:shape="rectangle">
            <gradient android:startColor="@color/start_color"
                android:endColor="@color/end_color"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>
 <com.google.android.material.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="55dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo"
        android:layout_marginHorizontal="26dp"
        tools:layout_editor_absoluteX="16dp"
        app:cornerRadius="10dp"
        android:textSize="20sp"
        android:text="Create an account"
        android:background="@drawable/create_acc_btn"
        android:fontFamily="@font/montserrat" />

您只需要修复您的渐变可绘制文件。

从中删除项目标签并放置 android xml 命名空间声明,如下所示:

<?xml version="1.0" encoding="utf-8"?>

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

    <gradient android:startColor="@color/start_color"
              android:endColor="@color/end_color"/>
    <corners android:radius="10dp"/>

</shape>

并将此行添加到您的按钮 xml 代码中:

app:backgroundTint="@null"

没有这个你的渐变背景将不会显示

注意: MaterialButton 管理自己的背景以控制高度、形状、颜色和状态。考虑使用 backgroundTint、shapeAppearance 和其他可用的属性。自定义背景将忽略这些属性,您应该考虑处理交互状态,例如按下、聚焦和禁用

您在使用自定义背景时也会失去连锁反应。