Android XML如何在ConstraintLayout中CardView与Activity背景间放置图片
实现方案
ConstraintLayout的子View层级由XML的声明顺序决定,越靠后声明的View层级越高。要让图片展示在Activity背景和CardView之间,只需把ImageView的声明放在CardView之前即可。
以下是修正后的完整XML代码(已修复你原代码中根布局ConstraintLayout与命名空间声明之间缺空格的笔误):
<?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="#D3E6ED" tools:context=".MainActivity"> <!-- 层级介于背景和CardView之间的图片 --> <ImageView android:id="@+id/insert_img" android:layout_width="120dp" android:layout_height="120dp" android:src="@mipmap/替换为你自己的图片资源名" android:scaleType="centerCrop" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="60dp"/> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="10dp" android:layout_marginTop="120dp" android:layout_marginEnd="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:cardCornerRadius="10dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
你可以根据实际需求调整ImageView的宽高、边距、对齐规则和图片资源,上述示例默认将图片顶部居中展示,刚好有一部分被顶部边距为120dp的CardView覆盖,匹配示例图的视觉效果。
内容的提问来源于stack exchange,提问作者Omar Saleem
相关产品推荐
相关产品推荐

