NestedScrolling机制

NestedScrolling机制(能够称为嵌套滚动或嵌套滑动)可以让父view和子view在滚动时进行配合,其基本流程以下:spa

  1. 当子view开始滚动以前,能够通知父view,让其先于本身进行滚动;
  2. 子view本身进行滚动
  3. 子view滚动以后,还能够通知父view继续滚动

要实现这样的交互,父View须要实现NestedScrollingParent接口,而子View须要实现NestedScrollingChild接口。.net

在这套交互机制中,child是动做的发起者,parent只是接受回调并做出响应。code

另外: 父view和子view并不须要是直接的父子关系,即若是“parent1包含parent2,parent2包含child”,则parent1和child仍能经过nestedScrolling机制进行交互。blog

  • NestedScrollView 已实现 NestedScrollingParent和NestedScrollingChild
  • RecyclerView 已实现 NestedScrollingChild
  • CoordinatorLayout 已实现 NestedScrollingParent

关于动做的方法大概能够分红两类继承

第一类:主要实现通用的的关联动做,各类view的改变均可以使用。接口

public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency)
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency)

第二类:主要实现滚动的动做ci

public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) 
public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) 
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target) 
public void onNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed)
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, View child, View target, float velocityX, float velocityY, boolean consumed) 
public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, View child, View target, float velocityX, float velocityY)

方法之间的具体对应关系以下:get

子(发起者) 父(被回调)
startNestedScroll onStartNestedScroll、onNestedScrollAccepted
dispatchNestedPreScroll onNestedPreScroll
dispatchNestedScroll onNestedScroll
stopNestedScroll onStopNestedScroll

流程源码

能够大体将嵌套滚动的流程归纳以下(以触摸滚动为例,惯性滚动(fling)的流程与此相似):it

  1. 调用child的startNestedScroll()来发起嵌套滚动流程(实质是寻找可以配合child进行嵌套滚动的parent)。parent的onStartNestedScroll()会被回调,若是此方法返回true,则onNestedScrollAccepted()也会被回调。
  2. child每次滚动前,能够先询问parent是否要滚动,即调用dispatchNestedPreScroll(),这会回调到parent的onNestedPreScroll(),parent能够在这个回调中先于child滚动。
  3. disdispatchNestedPreScroll()以后,child能够进行本身的滚动操做。
  4. child滚动之后,能够调用dispatchNestedScroll(),会回调到parent的onNestedScroll(),在这里parent能够进行后于child的滚动。 滚动结束,调用stopNestedScroll()。

其余

一、要关联滚动的View须要实现NestedScrollingChild接口,并在用NestedScrollingChildHelper辅助类处理相应的回调 二、须要关联滚动的View的父View须要实现NestedScrollingParent接口,可用NestedScrollingParentHelper辅助类处理相应的回调,并在相应的回调方法中处理动做 三、自定义Behavior要继承CoordinatorLayout.Behavior<V extends View> 四、CoordinatorLayout的直接子类设置layout_behavior属性才有效果(CoordinatorLayout会循环调用每一个子view的behavior)

参考:

NestedScrolling机制(一)——概述
http://blog.csdn.net/al4fun/article/details/53888990
源码看CoordinatorLayout.Behavior原理
http://blog.csdn.net/qibin0506/article/details/50377592
相关文章
相关标签/搜索