CardView:如何在保持半径的同时添加渐变背景

Tas*_*eni 13 xml android android-cardview

我想用 CardView 重新创建下面的图像。为此,我创建了一个渐变文件 (btn_gradient.xml),然后继续创建 CardView。

在此处输入图片说明

CardView 实现:

<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>
Run Code Online (Sandbox Code Playgroud)

除了半径消失而且这不是我想要的之外,一切都以这种方式正常工作。有没有办法可以直接在 CardView 上设置渐变?该cardBackgroundColor属性仅接受颜色,不接受可绘制对象。

任何帮助,将不胜感激。



附录:
根据要求,这是我的 btn_gradient.xml 文件:

<?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>
Run Code Online (Sandbox Code Playgroud)

小智 8

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/_10sdp"
    app:cardCornerRadius="@dimen/_10sdp"
    app:cardElevation="@dimen/_1sdp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/gradient_16"
        android:padding="@dimen/_6sdp">

    </LinearLayout>
</androidx.cardview.widget.CardView>
Run Code Online (Sandbox Code Playgroud)

和梯度就像

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#5B86E5"
        android:endColor="#36D1DC"
        android:angle="180" />

    <corners
        android:radius="10dp">
    </corners>
</shape>
Run Code Online (Sandbox Code Playgroud)

CardView card_radius 和渐变半径应该是相同的尺寸


小智 7

如果我可能会问,您是否有机会在棒棒糖之前的Android 设备上进行测试/运行?除了在 Android 4 上,您的代码似乎可以按您的意愿工作(显示渐变的弯角)。

为了实现对预棒棒糖设备所期望的结果,你可以添加<corners android:radius="4dp" />到您的@drawable/btn_gradient文件,(你就必须设置圆角半径匹配CardViewcardCornerRadius