NestedScrollView与behavior、layout_scrollFlags之间的关系

本文介绍了如何使用NestedScrollView实现与Toolbar的联动滚动效果。包括NestedScrollView的基本用法,如何设置behavior属性避免与Toolbar重叠,以及如何通过app:layout_scrollFlags属性控制Toolbar的隐藏与显示行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、声明为NestedScrollView的滚动布局无需设置其他属性即可触发折叠功效。
2、声明为behavior的view必须为CoordinatorLayout的直接子布局,可让他在toolbar下,不声明behavior的话会与toolbar重叠。
3、要让toolbar随NestedScrollView滚动的话需要设置app:layout_scrollFlags属性,取值一般为scroll|xxx,xxx有四个值:
enterAlways:向上滑时toolbar隐藏,向下滑动即展示。
enterAlwaysCollapsed:向上滑时toolbar隐藏,向下滑动直到NestedScrollView的底部时toolbar才展示。
exitUntilCollapsed:未知
snap:突然折断的意思,效果同enterAlwaysCollapsed,区别为滚动时手指离开屏幕时toolbar不会显示一半的状态,显示的部分大于一半时即全漏出来,小于一半时即隐藏掉。

注意:写了app:layout_scrollFlags属性的话布局会下移,假如有固定在底部的view可能会被挤出屏幕外。

<androidx.coordinatorlayout.widget.CoordinatorLayout android:id="@+id/parent_view" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- android:elevation="1dp"比header中的高,就会置上层--> <View android:id="@+id/toolBar" android:layout_width="match_parent" android:layout_height="100dp" android:layout_gravity="top" android:background="#627788" android:elevation="1dp" /> <!-- 顶部 Header(可以自定义内容) --> <LinearLayout android:id="@+id/header" android:layout_width="match_parent" android:layout_height="50dp" android:background="#6200EE" android:layout_marginTop="100dp" android:orientation="vertical"/> <WebView android:id="@+id/webView" android:layout_marginTop="150dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> 我有这样一个布局,我想控制上滑webview,header随之隐藏,下拉webview,header随之显示,使用如下代码: header.post { val initialHeaderHeight = header.height var initialHeight = 0 webView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY -> // 根据滚动距离调整header的高度 val newHeight = initialHeaderHeight.coerceAtMost(initialHeaderHeight - scrollY).coerceAtLeast(0) Log.d(TAG, "setOnScrollChangeListener, scrollY=$scrollY, oldScrollY=$oldScrollY, ") Log.d(TAG, "setOnScrollChangeListener, initialHeaderHeight=$initialHeaderHeight, scrollY=$scrollY, ") header.layoutParams.height = newHeight header.requestLayout() Log.d(TAG, "setOnScrollChangeListener, header.height=${header.height}") // 调整WebView的高度以填充剩余空间 if (initialHeight == 0) { initi
最新发布
03-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值