如何将布局背景置于ImageView后方且适配布局范围
看起来你遇到的核心问题是背景布局的层级和尺寸没有和ImageView做好适配,导致背景的边角会露在ImageView前方,同时可能超出ImageView的高度范围。我来帮你调整布局,完美实现你想要的效果:
修改后的布局代码
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/msg_bar" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent"> <!-- 背景布局:放在ImageView之前,作为底层绘制 --> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="wrap_content" android:layout_height="0dp" android:background="@color/black" app:layout_constraintStart_toEndOf="@+id/imageView" app:layout_constraintTop_toTopOf="@+id/imageView" app:layout_constraintBottom_toBottomOf="@+id/imageView"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0 MSGs" android:textColor="@color/white" android:paddingStart="@dimen/default_padding" android:padding="@dimen/small_padding" app:layout_constraintCenterVertical="true"/> </androidx.constraintlayout.widget.ConstraintLayout> <!-- ImageView:放在背景之后,覆盖在背景左侧 --> <ImageView android:id="@+id/imageView" android:layout_width="46dp" android:layout_height="0dp" app:layout_constraintDimensionRatio="W, 1:1" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:src="@drawable/ic_contact"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键修改点说明
调整绘制层级:
ConstraintLayout的绘制顺序是按XML中控件的先后顺序来的——先写的控件会被后写的控件覆盖。把背景布局放在ImageView前面,这样ImageView会刚好覆盖背景的左侧边缘,彻底解决背景边角露在ImageView前方的问题。绑定背景尺寸到ImageView:
给背景布局设置layout_height="0dp",并通过constraintTop和constraintBottom绑定到ImageView的上下边缘,让背景高度和ImageView完全一致,不会超出ImageView的尺寸范围。优化TextView布局:
给TextView添加constraintCenterVertical="true",让它在背景中垂直居中,视觉效果更协调。ImageView资源属性修正:
把android:background改成android:src——src是用来显示图标类资源的,background更适合设置背景色或填充型drawable,这样ImageView的图标显示会更正确。
后续你替换自定义drawable背景时,直接把android:background="@color/black"换成你的自定义drawable即可,布局结构已经帮你做好了适配,不会再出现之前的问题。
内容的提问来源于stack exchange,提问作者ibai.kar

