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 中,AppBarLayoutRecyclerView 常常配合 ScrollingViewBehavior 使用。请解释 ScrollingViewBehavior 的作用原理,以及它和 AppBarLayout.Behavior 的区别。

参考答案:

  • ScrollingViewBehavior 继承自 HeaderScrollingViewBehavior,作用是:

    1. 依赖 AppBarLayout
    2. AppBarLayout 滚动时,通过 offsetChildAsNeeded() 强制修改 RecyclerView/NestedScrollView 的 top,保证内容始终紧贴在 AppBarLayout 的底部,不会被遮挡。
  • AppBarLayout.Behavior 则负责 滚动事件的分发

    • 当用户向上滚动时,优先让 AppBarLayout 折叠;
    • 折叠完成后,剩余的滚动距离才交给 RecyclerView。
    • 从而实现「先折叠头部,再滚动内容」的经典效果。
  • 总结

    • ScrollingViewBehavior位置对齐
    • AppBarLayout.Behavior滚动逻辑

示例 当你滑动 ScrollView,TitleBar 的透明度会根据滚动距离渐变(比如 0~500px 内从透明变不透明)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class AlphaTitleBehavior(
context: Context,
attrs: AttributeSet
) : CoordinatorLayout.Behavior<View>(context, attrs) {

override fun layoutDependsOn(
parent: CoordinatorLayout,
child: View,
dependency: View
): Boolean {
// 指定依赖 ScrollView
return dependency is NestedScrollView
}

override fun onDependentViewChanged(
parent: CoordinatorLayout,
child: View, // 这里就是 TitleBar
dependency: View // 这里是 ScrollView
): Boolean {
val scrollView = dependency as NestedScrollView
val scrollY = scrollView.scrollY

// 计算透明度 (0f ~ 1f)
val alpha = (scrollY / 500f).coerceIn(0f, 1f)

child.alpha = alpha
return true
}
}


android-behavior
https://blog.201912.xyz/2025/09/18/android-behavior/
作者
jin123d
发布于
2025年9月18日
许可协议