如何实现带elevation阴影的CardView叠加在其他视图上方的效果

实现方案
要实现带elevation阴影的CardView叠加在其他视图上方的效果,可按以下步骤操作:
1. 布局实现
优先使用ConstraintLayout或者FrameLayout作为根布局,两类布局都天然支持子视图层叠显示,以下是ConstraintLayout的示例代码:
<!-- 根布局开启不裁剪子视图属性,避免CardView阴影被裁剪 --> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"> <!-- 上层背景区域,层级更低,写在布局前方 --> <LinearLayout android:id="@+id/top_bg_panel" android:layout_width="match_parent" android:layout_height="200dp" android:background="#2196F3" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <!-- 叠加显示的CardView,写在布局后方,elevation值大于0 --> <com.google.android.material.card.MaterialCardView android:layout_width="match_parent" android:layout_height="120dp" android:layout_marginHorizontal="16dp" app:cardCornerRadius="12dp" app:cardElevation="8dp" app:cardUseCompatPadding="true" <!-- 上下约束设置实现跨区域叠加效果 --> app:layout_constraintTop_toBottomOf="@id/top_bg_panel" app:layout_constraintBottom_toTopOf="@id/top_bg_panel" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"> <!-- CardView内部内容自行补充 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginStart="16dp" android:text="卡片内容" android:textSize="16sp"/> </com.google.android.material.card.MaterialCardView> <!-- 下方内容区域 --> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/top_bg_panel" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"> <!-- 下方业务内容自行补充 --> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
如果使用FrameLayout实现,只需要把CardView放在布局的最后位置即可,默认后渲染的子视图会覆盖在之前的子视图上方。
2. 阴影正常显示的注意事项
- 根布局需要添加
android:clipChildren="false"和android:clipToPadding="false"属性,避免CardView的阴影被父布局裁剪 - 优先使用MaterialCardView的
app:cardElevation属性设置阴影高度,兼容性比原生android:elevation更好 - 如需适配Android 5.0以下系统,添加
app:cardUseCompatPadding="true"属性即可开启兼容阴影模式 - 可以通过调整elevation值控制视图层级,elevation值越大的视图显示层级越高,不需要刻意调整布局内的视图书写顺序
内容的提问来源于stack exchange,提问作者Ahmed Mamdouh
相关产品推荐
相关产品推荐

