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
相關文章
相關標籤/搜索