CardView: How do I add a gradient background while maintaining the radius

Issue

I want to re-create the image below with a CardView. To achieve this, I created a gradient file (btn_gradient.xml) and then proceeded to create the CardView.

enter image description here

CardView implementation:

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:layout_margin="25dp"
        app:cardElevation="0dp"
        app:cardCornerRadius="4dp"
        app:cardPreventCornerOverlap="false">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@drawable/btn_gradient"
            android:text="Create Account"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textAllCaps="false"/>


    </android.support.v7.widget.CardView>

Everything works fine this way except that the radius disappears and this is not what I want. Is there a way I can set the gradient directly on the CardView? The cardBackgroundColor attribute accepts only colors, not drawables.

Any help would be appreciated.

Addendum:
As requested, this is my btn_gradient.xml file:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:type="linear"
    android:angle="0"
    android:startColor="#ffc200"
    android:endColor="#fca10b" />
</shape>

Solution

If I may ask, are you per-chance testing/running on a pre-lollipop Android device? Your code seems to work as you desire (curved corners showing with the gradient) except on Android 4.

To achieve the desired result on pre-lollipop devices, you can add <corners android:radius="4dp" /> to your @drawable/btn_gradient file, (you would have to set the corner radius to match the CardView‘s cardCornerRadius.

Answered By – Michio

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *