ConstraintLayout前景视图覆盖子布局问题解决方案咨询
解决父ConstraintLayout前景图覆盖子布局的问题
Android中android:foreground属性的设计逻辑就是绘制在View的所有子元素之上,所以你当前的写法必然会让前景图盖在子ConstraintLayout上方。要实现前景图在子布局后方的效果,需要调整布局结构,把前景图作为父布局的一个子View放在层级最底部。
修改后的完整XML代码如下:
<?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:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:forceHasOverlappingRendering="false"> <!-- 作为背景层的前景图,放在所有子布局最前面,会被后续布局覆盖 --> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/deviworkslogo_only_gears_white" android:tint="#E6E6E6" android:tintMode="src_in" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/constraintLayout" android:layout_width="fill_parent" android:layout_height="100dp" android:background="#D31212" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"> <Button android:id="@+id/homeBtn" android:layout_width="60dp" android:layout_height="60dp" android:layout_marginEnd="30dp" android:foreground="@drawable/ic_home_black_24dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/libraryBtn" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/libraryBtn" android:layout_width="60dp" android:layout_height="60dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/settingsBtn" android:layout_width="60dp" android:layout_height="60dp" android:layout_marginStart="30dp" android:foreground="@drawable/ic_settings_black_24dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@+id/libraryBtn" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="250dp" android:layout_height="0dp" android:background="#3973AF" app:layout_constraintBottom_toTopOf="@+id/constraintLayout" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
修改说明:
- 移除父布局的
android:foreground系列属性,因为它们的作用就是在子元素上方绘制内容 - 添加一个
ImageView作为父布局的第一个子View,完全复用原来前景图的资源、着色和居中逻辑 - 由于布局层级是按XML顺序绘制的,先写的View会被后写的View覆盖,所以这个ImageView会处于所有子ConstraintLayout的后方,达到你想要的效果
内容的提问来源于stack exchange,提问作者CharlyCM
相关产品推荐
相关产品推荐

