如何实现Toolbar始终悬浮在全屏RecyclerView上方的效果
解决Toolbar被RecyclerView遮挡的问题
你的问题核心是RecyclerView的约束范围覆盖了Toolbar的区域,同时在ConstraintLayout中,后声明的控件会绘制在前面的控件之上,导致Toolbar被遮挡。只需修改RecyclerView的布局约束即可解决:
修改布局XML中的RecyclerView约束
将RecyclerView的app:layout_constraintTop_toTopOf="parent"改为app:layout_constraintTop_toBottomOf="@id/toolbar",这样RecyclerView会从Toolbar的底部开始布局,既保证RecyclerView占满剩余全屏空间,又不会遮挡Toolbar:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:tag="@string/tagMain" tools:context=".fragments.MainItemFragment"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/top_controls_background" android:minHeight="?attr/actionBarSize" android:theme="?attr/actionBarTheme" app:menu="@menu/options_movie" android:fitsSystemWindows="true" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textSize="20sp" android:textStyle="bold" android:textColor="@color/white" android:text="@string/app_name"/> </androidx.appcompat.widget.Toolbar> <androidx.recyclerview.widget.RecyclerView android:id="@+id/mainRecyclerView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" <!-- 修改这一行的约束 --> app:layout_constraintTop_toBottomOf="@id/toolbar" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
额外说明
- 此修改后,Toolbar会始终悬浮在RecyclerView上方,RecyclerView滚动时不会影响Toolbar的显示
- 你的Adapter代码无需修改,问题完全出在布局约束上
内容的提问来源于stack exchange,提问作者Herminio Developer
相关产品推荐
相关产品推荐

