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

Time:12-21

I want to make a gradient button in an Android app that I'm developing in Kotlin. I have made the drawable file for the gradient background but when I do give the button the customized background it doesn't work, nothing changes. This is the code for the gradient background and below that is the XML code for the button.

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

CodePudding user response:

You just have to fix your gradient drawable file.

remove the item tag from it and put android xml namespace declaration like this :

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

And add this line to your button xml code :

app:backgroundTint="@null"

without this your gradient background won't show up

Note : MaterialButton manages its own background to control elevation, shape, color and states. Consider using backgroundTint, shapeAppearance and other attributes where available. A custom background will ignore these attributes and you should consider handling interaction states such as pressed, focused and disabled

You are also going to lose ripple effect when using custom background.

  • Related