首页 > 解决方案 > Android CardView 投影被剪裁

问题描述

我正在尝试在 CardView 上显示阴影。如果我将 CardView 放入容器(如 LinearLayout),阴影将无法正确显示。

我的代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFF8"
    android:clipToPadding="false"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:translationZ="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

    <LinearLayout
        android:id="@+id/card1"
        android:layout_width="match_parent"
        android:layout_height="330dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:background="#FFFFF8"
        android:clipToPadding="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.cardview.widget.CardView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:translationZ="16dp"
            />
    </LinearLayout>
    
</androidx.constraintlayout.widget.ConstraintLayout>



看起来像:

在此处输入图像描述

我有两个CardViews,我把下面的一个放到 aLinearLayout中,如你所见,它的顶部和左侧没有阴影。但是上面的看起来不错。

当 CardView 在 LinearLayout 中时,有什么方法可以解决这种情况吗?

PS:

关于为什么我不想有额外的边距或填充的更多上下文,我的应用程序是数据驱动的,与 CardViews 上的阴影相同,CardViews 可以垂直或水平一一布局,有或没有阴影在他们身上,如果我必须考虑额外的边距,以显示带有阴影的 CardViews,那么逻辑就会太复杂。

假设这样一个场景,比如说一个阴影 CardView,另一个阴影向右;但是一个没有阴影到底部等。我必须将边距设置到第一个但不设置到右边,因为第二个(在右侧)也有阴影,而对于第二个,我有阴影的右边距;与下面的逻辑相同,但逻辑在这里变得复杂,这就是为什么我在这里寻求解决方案,如果投影可以在不依赖边距/填充的情况下可见,那对我来说太好了。

编辑:关闭,因为:https ://stackoverflow.com/a/57741227/853191 ,这条评论帮助了我。

谢谢!

标签: androidcardviewdropshadow

解决方案


要显示阴影,您应该使用 android:translationX="16dp", android:translationY="16dp", android:translationZ="16dp"如下所示。

<LinearLayout
    android:id="@+id/card1"
    android:layout_width="match_parent"
    android:layout_height="330dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:background="#FFFFF8"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.cardview.widget.CardView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:translationX="16dp"
        android:translationY="16dp"
        android:translationZ="16dp" />
</LinearLayout>

输出: 输出图像点击这里!


推荐阅读