最终效果:
1. 接口
NestedScrollingParent
用来配置子视图( NestedScrollingChild
)嵌套滚动。
NestedScrollingParent
简称 NP
NestedScrollingChild
简称 NC
- NC 产生一个 touch 事件,调用
startNestedScroll
,表示开始分享出去 touch 事件, NP 的onStartNestedScroll
判断是否需要跟 NC 配合,返回 true 表示接受 - NC 调用
dispatchNestedPreScroll
,通知 NP 将要进行一个 Touch 事件,如移动 5个像素,NP 的onNestedPreScroll
中收到通知,知道 NC 要准备移动5个像素,这时候 NP 正好也需要滑动 2 个像素,然后在onNestedPreScroll
的参数consumed[]
数组对应的方向(下标为0的x轴,下标为1的y轴)赋值 2,表示消费 2 个像素 NC 拿到
consumed[]
数组,知道 NP 消费了 2 个像素,剩下了 3 个像素,然后自己根据需要再移动 3 个像素的距离,如果这时候 NC 由于某个原因只移动了 2 个像素,那么剩下的 1 个像素距离会调用dispatchNestedScroll
给 NP,NP 在onNestedScroll
处理剩下的未消费的 1 像素。最后,NC 调用stopNestedScroll
,最后 NP 调用onStopNestedScroll
结束。同 NestedScroll 类似的还有一套 NestedFling 操作,整体流程类似,NC 快速滑动产生一个 fling 事件,处理流程 NC.
dispatchNestedPreFling
-> NP.onNestedPreFling
-> NC.dispatchNestedFling
-> NP.onNestedFling
为什么 NC 和 NP 能相互配合滚动? 主要的源码在 NestedScrollingChildHelper 和 NestedScrollingParentHelper
效果实现
自定 ViewGroup ,实现 NestedScrollingParent
接口,一个 NestedScrollingParentHelper
成员变量作为辅助
布局
<?xml version="1.0" encoding="utf-8"?>
<xyz.hanks.nestedwebview.nestedscroll.NScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#20f0"
android:scrollbarSize="3dp"
android:scrollbars="vertical"/>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e1e1e1"
android:orientation="verti