android-behavior
ScrollingViewBehavior & HeaderScrollingViewBehavior 总结
1. HeaderScrollingViewBehavior
- 抽象基类,专门为 依赖 header(头部视图)的联动场景 提供通用逻辑。
- 主要职责:
findFirstDependency():子类指定依赖的 header。getScrollRange():计算 header 的滚动范围。- 在
onMeasureChild/onLayoutChild自动适配 child 的 top 和高度。
- 自身不会直接用,通常作为基类。
2. AppBarLayout.ScrollingViewBehavior
- 继承
HeaderScrollingViewBehavior,依赖的 header 是 AppBarLayout。 - 核心逻辑:
- 在
onDependentViewChanged→ 调用offsetChildAsNeeded(),强制修改 child 的 top,让它紧贴 AppBarLayout 的 bottom。 - 配合
AppBarLayout.Behavior实现「先折叠 Toolbar,再滚动 RecyclerView/NestedScrollView」。
- 在
3. 职责分工
- ScrollingViewBehavior:负责 位置联动(修改 child.top)。
- AppBarLayout.Behavior:负责 滚动事件分发(先折叠 header,再交给 child 滚动)。
面试题
题目:
在 CoordinatorLayout 中,AppBarLayout 和 RecyclerView 常常配合 ScrollingViewBehavior 使用。请解释 ScrollingViewBehavior 的作用原理,以及它和 AppBarLayout.Behavior 的区别。
参考答案:
ScrollingViewBehavior继承自HeaderScrollingViewBehavior,作用是:- 依赖
AppBarLayout; - 在
AppBarLayout滚动时,通过offsetChildAsNeeded()强制修改 RecyclerView/NestedScrollView 的 top,保证内容始终紧贴在AppBarLayout的底部,不会被遮挡。
- 依赖
AppBarLayout.Behavior则负责 滚动事件的分发:- 当用户向上滚动时,优先让
AppBarLayout折叠; - 折叠完成后,剩余的滚动距离才交给 RecyclerView。
- 从而实现「先折叠头部,再滚动内容」的经典效果。
- 当用户向上滚动时,优先让
总结:
ScrollingViewBehavior管 位置对齐;AppBarLayout.Behavior管 滚动逻辑。
示例 当你滑动 ScrollView,TitleBar 的透明度会根据滚动距离渐变(比如 0~500px 内从透明变不透明)。
1 | |
android-behavior
https://blog.201912.xyz/2025/09/18/android-behavior/