Android Support Design 中 CoordinatorLayout 與 Behaviors 初探

Android M Preview發佈後,咱們得到了一個新的support library —— Android Design Support Library 用來實現Google的Material Design 提供了一系列符合設計標準的控件。html

其中有衆多的控件,其中最複雜,功能最強大的就是CoordinatorLayout,顧名思義,它是用來組織它的子views之間協做的一個父view。CoordinatorLayout默認狀況下可理解是一個FrameLayout,它的佈局方式默認是一層一層疊上去。
那麼,CoordinatorLayout的神奇之處就在於Behavior對象了。
看下CoordinatorLayout.Behavior對象的 Overviewjava

Interaction behavior plugin for child views of CoordinatorLayout.android

A Behavior implements one or more interactions that a user can take on a child view. These interactions may include drags, swipes, flings, or any other gestures.segmentfault

可知Behavior對象是用來給CoordinatorLayout的子view們進行交互用的。
Behavior接口擁有不少個方法,咱們拿AppBarLayout爲例。AppBarLayout中有兩個Behavior,一個是拿來給它本身用的,另外一個是拿來給它的兄弟結點用的,咱們重點關注下AppBarLayout.ScrollingViewBehavior這個類。佈局

咱們看下這個類中的如下方法設計

0. dependency

javapublic boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency)     {
    return dependency instanceof AppBarLayout;
}

這個方法告訴CoordinatorLayout,這個view是依賴AppBarLayout的,後續父親能夠利用這個方法,查找到這個child全部依賴的兄弟結點。代理

1. measure

javapublic boolean onMeasureChild(CoordinatorLayout parent, View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)

這個是CoordinatorLayout在進行measure的過程當中,利用Behavior對象對子view進行大小測量的一個方法。
在這個方法內,咱們能夠經過parent.getDependencies(child);這個方法,獲取到這個child依賴的view,而後經過獲取這個child依賴的view的大小來決定自身的大小。code

2. layout

javapublic boolean onLayoutChild(CoordinatorLayout parent, View child, int layoutDirection)

這個方法是用來子view用來佈局自身使用,若是依賴其餘view,那麼系統會首先調用htm

javapublic boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency)

這個方法,能夠在這個回調中記錄dependency的一些位置信息,在onLayoutChild中利用保存下來的信息進行計算,而後獲得自身的具體位置。對象

3. nested scroll

javapublic boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes)
javapublic void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed)
javapublic void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)
javapublic void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target)

這幾個方法是否是特別熟悉?我在Android嵌套滑動機制(NestedScrolling) 介紹過,這幾個方法恰好是NestedScrollingParent的方法,也就是對CoodinatorLayout進行的一個代理(Proxy),即CoordinatorLayout本身不對這些消息進行處理,而是傳遞給子view的Behavior,進行處理。利用這樣的方法,實現了view和view之間的交互和視覺的協同(佈局、滑動)。

總結

能夠看到CoodinatorLayout給咱們實現了一個能夠被子view代理實現方法的一個佈局。這和傳統的ViewGroup不一樣,子view今後知道了彼此之間的存在,一個子view的變化能夠通知到另外一個子view。CoordinatorLayout所作的事情就是當成一個通訊的橋樑,鏈接不一樣的view。使用Behavior對象進行通訊。

咱們具體的實現能夠參照 Android官方文檔告訴咱們的每個方法的做用 進行重寫,實現本身想要的各類複雜的功能。
https://developer.android.com/reference/android/support/design/widget/... 有了這麼一套機制,想實現組件之間的交互,就更加方便快捷啦~

相關文章
相關標籤/搜索