如何在带Bottom Navigation的ListView中平滑滚动时隐藏Toolbar
这个问题的核心原因是你把所有组件都嵌套在了LinearLayout里——CoordinatorLayout的滚动联动行为(比如AppBarLayout的滚动隐藏、滚动视图的跟随联动)要求相关组件必须直接作为CoordinatorLayout的子View才能生效,外层的LinearLayout会阻断Behavior的事件传递,所以导致Toolbar滚动隐藏功能失效。
下面是修复后的完整布局代码,我会同步解决几个关键问题:
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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="wahwah.ahmed.google.waheed.app.ninews.android.com.ninewsapp.MainActivity"> <!-- AppBar区域:添加滚动属性让Toolbar可以滚动隐藏 --> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" <!-- 关键:添加滚动标记,让Toolbar可以随滚动隐藏/显示 --> app:layout_scrollFlags="scroll|enterAlways" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="scrollable" /> </android.support.design.widget.AppBarLayout> <!-- 主内容区域:用Behavior和AppBar联动 --> <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- 阴影View固定在顶部,不需要Behavior --> <View android:id="@+id/gradientShadow" android:layout_width="match_parent" android:layout_height="7dp" android:background="@drawable/dropshadow" /> </FrameLayout> <!-- BottomNavigationView:用anchor固定在底部,不影响滚动 --> <android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/windowBackground" app:menu="@menu/navigation" <!-- 关键:锚定到CoordinatorLayout底部,确保固定在屏幕下方 --> app:layout_anchor="@id/content" app:layout_anchorGravity="bottom" /> </android.support.design.widget.CoordinatorLayout>
几个关键修改点说明:
- 替换外层布局:把原来的LinearLayout换成CoordinatorLayout,这是滚动联动生效的基础
- 给Toolbar添加滚动标记:
app:layout_scrollFlags="scroll|enterAlways",这个属性控制Toolbar随滚动的行为(scroll表示会随滚动隐藏,enterAlways表示向下滚动时立即显示) - 调整BottomNavigationView的定位:通过
layout_anchor和layout_anchorGravity让它固定在内容区域的底部,避免遮挡主内容,同时不影响AppBar的滚动联动 - 移除冗余Behavior:主内容区域的FrameLayout已经设置了
appbar_scrolling_view_behavior,内部的ViewPager和阴影View不需要重复设置
这样修改后,当ListView(或者ViewPager里的滚动组件)滚动时,Toolbar就会正常隐藏/显示了。
内容的提问来源于stack exchange,提问作者Ahmed Waheed
相关产品推荐
相关产品推荐

