Xamarin Android中如何实现ListView向下滚动时隐藏Toolbar
解决方案
问题根源
你当前的方案不生效主要有两个核心原因:
layout_scrollFlags属性作用对象错误,该属性需要配置给AppBarLayout的直接子控件,而非AppBarLayout本身- ListView默认未开启嵌套滚动能力,无法触发CoordinatorLayout的滚动联动逻辑
步骤1:修正根布局XML配置
你需要将原来写在AppBarLayout上的layout_scrollFlags移到Toolbar节点,同时调整参数匹配你的滚动需求,修正后的完整代码如下:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 将scrollFlags配置到Toolbar节点 --> <android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical"/> </android.support.v7.widget.Toolbar> <!-- TabLayout不配置scrollFlags,默认固定在顶部 --> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="32dp" android:layout_below="@id/title" android:layout_marginBottom="4dp" app:tabMinWidth="96dp" app:tabIndicatorHeight="4dp" app:tabIndicatorFullWidth="false" app:tabMode="scrollable"> <android.support.design.widget.TabItem android:text="@string/tab_1"/> <android.support.design.widget.TabItem android:text="@string/tab_2"/> <android.support.design.widget.TabItem android:text="@string/tab_3"/> </android.support.design.widget.TabLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> </android.support.design.widget.CoordinatorLayout>
注:可以删除ViewPager的
android:layout_below="@id/appbar"属性,appbar_scrolling_view_behavior会自动处理位置关系。
步骤2:开启ListView的嵌套滚动能力
在每个Tab对应的Fragment布局中,给ListView节点添加嵌套滚动属性即可:
<ListView android:id="@+id/your_listview" android:layout_width="match_parent" android:layout_height="match_parent" <!-- 开启嵌套滚动,API21及以上原生支持,匹配你的API30运行环境 --> android:nestedScrollingEnabled="true" />
可选兼容方案(仅需兼容API21以下时使用)
如果你的应用需要支持API21以下系统,可以用android.support.v4.widget.NestedScrollView包裹ListView,注意此时需要将ListView的高度设为wrap_content,并关闭ListView的自身滚动:
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ListView android:id="@+id/your_listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:nestedScrollingEnabled="false" /> </RelativeLayout> </android.support.v4.widget.NestedScrollView>
内容的提问来源于stack exchange,提问作者Carnagion
相关产品推荐
相关产品推荐

