strokeColor 和 strokeWidth 在 androidx.cardview.widget.CardView android 中不起作用

strokeColor and strokeWidth not working in androidx.cardview.widget.CardView android

正在尝试在 cardView (androidx.cardview.widget.CardView)

周围制作一些边框

代码如下:

<androidx.cardview.widget.CardView

    android:id="@+id/cardView"
    android:layout_width="273dp"
    android:layout_height="118dp"
    android:layout_marginStart="9dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="9dp"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical"
    app:cardCornerRadius="8dp"

    android:background="@drawable/fix_border" 
    app:strokeColor="#dedede"
    app:strokeWidth="3dp">

</androidx.cardview.widget.CardView>

结果:

也试过使用自定义形状作为背景(fix_border.xml),也没用。

fix_border.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="2dp"
        android:color="#dedede" />
    <!--    <solid android:color="#ffffff" />-->
    <padding
        android:bottom="7dp"
        android:left="7dp"
        android:right="7dp"
        android:top="7dp" />
</shape>

无法为CardView(参考:v7 cardview library issues)提供可绘制背景,但可以给它app:cardBackgroundColor,但如果需要描边,您可以在其中添加一个布局,并向其中添加带有描边的可绘制背景,这样就可以了。所以,像这样:

<androidx.cardview.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="273dp"
    android:layout_height="118dp"
    android:layout_marginStart="9dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="9dp"
    android:padding="10dp"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical"
    app:cardCornerRadius="8dp">
    <!-- Any layout type here -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fix_border">
        <!-- Build your layout, with a background stroke! -->
    </RelativeLayout>
</androidx.cardview.widget.CardView>

只需使用 Material Components Library 和扩展 androidx.cardview.widget.CardViewMaterialCardView
类似于:

    <com.google.android.material.card.MaterialCardView
        app:strokeColor="@color/primaryDarkColor"
        app:strokeWidth="3dp"
        ../>