设置显示在RecyclerView旁的箭头控件始终覆盖在其上方如何解决
问题原因
覆盖问题由两个布局配置错误共同导致:
- ConstraintLayout中,子控件设置
match_parent作为宽/高时,会直接占满父布局对应方向的尺寸,无视自身设置的start/end或top/bottom约束。你的RecyclerView设置了android:layout_width="match_parent",哪怕指定了右端约束在箭头左侧,也会直接占满父布局宽度,自然就和右侧的箭头重叠。 - 你只给TextView设置了底部约束到RecyclerView顶部,但没有给RecyclerView设置顶部约束到TextView底部,RecyclerView的垂直位置也会出现异常。
修复步骤
- 将RecyclerView的
android:layout_width属性从match_parent改为0dp(对应ConstraintLayout的match_constraint,会按照约束的起止边界自动计算宽度) - 给RecyclerView补充
app:layout_constraintTop_toBottomOf="@id/tv_news_title"约束,固定垂直位置 - 可选:如果要让箭头和RecyclerView垂直居中对齐,可以把箭头的top和bottom约束改为和RecyclerView对齐,替换原来对齐基准线的配置
- 可选:如果RecyclerView内容较多时要避免撑出边界,可额外给RecyclerView添加
app:layout_constrainedHeight="true"属性,确保高度不会超出上下约束的范围
修改后的核心代码片段
<?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" tools:context=".ui.home.HomeActivity"> <androidx.constraintlayout.widget.Guideline android:id="@+id/gl_50" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" app:layout_constraintGuide_percent="0.5" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/gl_75" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" app:layout_constraintGuide_percent="0.75" /> <TextView android:id="@+id/tv_news_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/news_main_title" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@color/black" app:layout_constraintBottom_toTopOf="@+id/rv_news" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@id/gl_50"/> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_news" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" app:layout_constrainedHeight="true" app:layout_constraintTop_toBottomOf="@id/tv_news_title" app:layout_constraintBottom_toTopOf="@+id/gl_75" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/ibtn_arrow"/> <ImageButton android:id="@+id/ibtn_arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/ic_baseline_arrow_forward" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@id/rv_news" app:layout_constraintBottom_toBottomOf="@id/rv_news" /> </androidx.constraintlayout.widget.ConstraintLayout>
内容的提问来源于stack exchange,提问作者dazai
相关产品推荐
相关产品推荐

