2019獨角獸企業重金招聘Python工程師標準>>>
NestedScrolling機制(可以稱為嵌套滾動或嵌套滑動)能夠讓父view和子view在滾動時進行配合,其基本流程如下:
- 當子view開始滾動之前,可以通知父view,讓其先于自己進行滾動;
- 子view自己進行滾動
- 子view滾動之后,還可以通知父view繼續滾動
要實現這樣的交互,父View需要實現NestedScrollingParent接口,而子View需要實現NestedScrollingChild接口。
在這套交互機制中,child是動作的發起者,parent只是接受回調并作出響應。
另外: 父view和子view并不需要是直接的父子關系,即如果“parent1包含parent2,parent2包含child”,則parent1和child仍能通過nestedScrolling機制進行交互。
- 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)
第二類:主要實現滾動的動作
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)
方法之間的具體對應關系如下:
子(發起者) | 父(被回調) |
---|---|
startNestedScroll | onStartNestedScroll、onNestedScrollAccepted |
dispatchNestedPreScroll | onNestedPreScroll |
dispatchNestedScroll | onNestedScroll |
stopNestedScroll | onStopNestedScroll |
流程
可以大致將嵌套滾動的流程概括如下(以觸摸滾動為例,慣性滾動(fling)的流程與此類似):
- 調用child的startNestedScroll()來發起嵌套滾動流程(實質是尋找能夠配合child進行嵌套滾動的parent)。parent的onStartNestedScroll()會被回調,如果此方法返回true,則onNestedScrollAccepted()也會被回調。
- child每次滾動前,可以先詢問parent是否要滾動,即調用dispatchNestedPreScroll(),這會回調到parent的onNestedPreScroll(),parent可以在這個回調中先于child滾動。
- disdispatchNestedPreScroll()之后,child可以進行自己的滾動操作。
- child滾動以后,可以調用dispatchNestedScroll(),會回調到parent的onNestedScroll(),在這里parent可以進行后于child的滾動。 滾動結束,調用stopNestedScroll()。
其他
1、要關聯滾動的View需要實現NestedScrollingChild接口,并在用NestedScrollingChildHelper輔助類處理相應的回調 2、需要關聯滾動的View的父View需要實現NestedScrollingParent接口,可用NestedScrollingParentHelper輔助類處理相應的回調,并在相應的回調方法中處理動作 3、自定義Behavior要繼承CoordinatorLayout.Behavior<V extends View> 4、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