问题描述
我正在尝试在 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>
看起来像:
我有两个 CardView
,我将下面的一个放入 LinearLayout
,如您所见,顶部和左侧没有阴影。但上面的看起来不错。
CardView 在 LinearLayout 中的情况有什么办法可以解决吗?
附注:
- 我不想在 CardView 上引入额外的边距或向容器 LinearLayout 引入额外的填充
- 我尝试将
android:clipToPadding="false"
添加到容器 LinearLayout,但没有帮助。 - 我已阅读此 Elevation shadow is clipped,并尝试了
android:clipToPadding="false"
&&android:clipChildren="false"
,但它不起作用。
更多关于为什么我不想有额外的边距或填充的上下文,我的应用程序是数据驱动的,与 CardViews 上的阴影相同,CardViews 可以垂直或水平地一一布局,有或有没有阴影,如果我必须考虑额外的边距来显示带有阴影的 CardView,那么逻辑会太复杂。
假设这样一个场景,比如说一个阴影的 CardView,另一个阴影在右边;但一个没有阴影到底部等。我必须将边距设置在第一个左边但没有设置在右边,因为第二个(右侧)也有阴影,对于第二个,我有阴影的右边距;与下面的逻辑相同,但这里的逻辑变得复杂,这就是为什么我在这里要求解决方案,如果阴影可以在不依赖边距/填充的情况下可见,那对我来说会很棒。
编辑:关闭,因为:https://stackoverflow.com/a/57741227/853191,这条评论帮助了我。
谢谢!
解决方法
要显示您应该使用的阴影 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>