Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

CoordinatorLayout 中 Behavior 源碼淺析

編輯:關於 Android 程式設計

當給 CoordinatorLayout 的直接子 View 設置 Behavior 後,CoordinatorLayout 的一些事件就能傳入 Behavior,Behavior 再指導 View 做相應處理。本文從源碼角度梳理 Behavior 的實例化過程與各類回調的觸發時機。

Behavior 對象是怎麼被實例化的

CoordinatorLayout 的子 View 是怎麼拿到 Behavior 對象的?設置 Behavior 有兩種方式:

1. 代碼裡直接設置:child.getLayoutParams().setBehavior(),這種情況比較直白。

2. XML 裡設置 app:layout_behavior="",這種情況 Behavior 通過反射實例化。

對應第二種情況,看看 CoordinatorLayout 的 LayoutParams 兩個參數的構造函數:

 LayoutParams(Context context, AttributeSet attrs) { super(context, attrs); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CoordinatorLayout_LayoutParams); this.gravity = a.getInteger( R.styleable.CoordinatorLayout_LayoutParams_android_layout_gravity, Gravity.NO_GRAVITY); mAnchorId = a.getResourceId(R.styleable.CoordinatorLayout_LayoutParams_layout_anchor, View.NO_ID); this.anchorGravity = a.getInteger(R.styleable.CoordinatorLayout_LayoutParams_layout_anchorGravity, Gravity.NO_GRAVITY); this.keyline = a.getInteger(R.styleable.CoordinatorLayout_LayoutParams_layout_keyline, -1); mBehaviorResolved = a.hasValue( R.styleable.CoordinatorLayout_LayoutParams_layout_behavior); if (mBehaviorResolved) { mBehavior = parseBehavior(context, attrs, a.getString( R.styleable.CoordinatorLayout_LayoutParams_layout_behavior)); } a.recycle(); }

可以看到,當檢測到設置了 app:layout_behavior="" 時,就調用 parseBehavior 函數,利用反射實例化出 Behavior 對象。

Behavior 的分類分析

Behavior 都是配合 CoordinatorLayout 使用的,可分為三種情況:

1. onInterceptTouchEvent + onTouchEvent:處理觸摸事件。

2. layoutDependsOn + onDependentViewChanged + onDependentViewRemoved:處理 View 引起的變化。

3. onStartNestedScroll + onNestedScrollAccepted + onStopNestedScroll + onNestedScroll + onNestedPreScroll + onNestedFling + onNestedPreFling:處理嵌套滑動引起的變化。

我們先大致了解每種情況下各函數的調用時機與作用。

onInterceptTouchEvent + onTouchEvent

分兩部分考慮:一是 CoordinatorLayout 如何調用指定 View 的 Behavior 的這兩個函數;二是 Behavior 內部具體做了什麼(這部分由自定義 Behavior 決定,先不管)。先看 CoordinatorLayout 的 onInterceptTouchEvent:

 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { MotionEvent cancelEvent = null; final int action = MotionEventCompat.getActionMasked(ev); // Make sure we reset in case we had missed a previous important event. if (action == MotionEvent.ACTION_DOWN) { resetTouchBehaviors(); } final boolean intercepted = performIntercept(ev, TYPE_ON_INTERCEPT); if (cancelEvent != null) { cancelEvent.recycle(); } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { resetTouchBehaviors(); } return intercepted; }

這裡調用了 performIntercept,參數 type 用 TYPE_ON_INTERCEPT 表示從 onInterceptTouchEvent 進來,TYPE_ON_TOUCH 表示從 onTouchEvent 進來:

 private boolean performIntercept(MotionEvent ev, final int type) { boolean intercepted = false; boolean newBlock = false; MotionEvent cancelEvent = null; final int action = MotionEventCompat.getActionMasked(ev); final List<View> topmostChildList = mTempList1; getTopSortedChildren(topmostChildList); // Let topmost child views inspect first final int childCount = topmostChildList.size(); for (int i = 0; i < childCount; i++) { final View child = topmostChildList.get(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final Behavior b = lp.getBehavior(); if ((intercepted || newBlock) && action != MotionEvent.ACTION_DOWN) { // Cancel all behaviors beneath the one that intercepted. // If the event is "down" then we don't have anything to cancel yet. if (b != null) { if (cancelEvent != null) { final long now = SystemClock.uptimeMillis(); cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); } switch (type) { case TYPE_ON_INTERCEPT: b.onInterceptTouchEvent(this, child, cancelEvent); break; case TYPE_ON_TOUCH: b.onTouchEvent(this, child, cancelEvent); break; } } continue; } if (!intercepted && b != null) { switch (type) { case TYPE_ON_INTERCEPT: intercepted = b.onInterceptTouchEvent(this, child, ev); break; case TYPE_ON_TOUCH: intercepted = b.onTouchEvent(this, child, ev); break; } if (intercepted) { mBehaviorTouchView = child; } } // Don't keep going if we're not allowing interaction below this. // Setting newBlock will make sure we cancel the rest of the behaviors. final boolean wasBlocking = lp.didBlockInteraction(); final boolean isBlocking = lp.isBlockingInteractionBelow(this, child); newBlock = isBlocking && !wasBlocking; if (isBlocking && !newBlock) { // Stop here since we don't have anything more to cancel - we already did // when the behavior first started blocking things below this point. break; } } topmostChildList.clear(); return intercepted; }

從遍歷開始,第一個 if 的作用是:如果已有 View 的 Behavior 攔截了事件且當前不是 ACTION_DOWN,則其他 View 的 Behavior 都會收到 ACTION_CANCEL。第二個 if 則在未被攔截且存在 Behavior 時,調用對應的 onInterceptTouchEvent 或 onTouchEvent。

再看 CoordinatorLayout 的 onTouchEvent:

 @Override public boolean onTouchEvent(MotionEvent ev) { boolean handled = false; boolean cancelSuper = false; MotionEvent cancelEvent = null; final int action = MotionEventCompat.getActionMasked(ev); if (mBehaviorTouchView != null || (cancelSuper = performIntercept(ev, TYPE_ON_TOUCH))) { // Safe since performIntercept guarantees that // mBehaviorTouchView != null if it returns true final LayoutParams lp = (LayoutParams) mBehaviorTouchView.getLayoutParams(); final Behavior b = lp.getBehavior(); if (b != null) { handled = b.onTouchEvent(this, mBehaviorTouchView, ev); } } // Keep the super implementation correct if (mBehaviorTouchView == null) { handled |= super.onTouchEvent(ev); } else if (cancelSuper) { if (cancelEvent != null) { final long now = SystemClock.uptimeMillis(); cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); } super.onTouchEvent(cancelEvent); } if (!handled && action == MotionEvent.ACTION_DOWN) { } if (cancelEvent != null) { cancelEvent.recycle(); } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { resetTouchBehaviors(); } return handled; }

onTouchEvent 的邏輯是:看當前事件是否被某個 View 的 Behavior 感興趣,感興趣就交給 Behavior 處理,否則由 CoordinatorLayout 自己處理。這樣就完成了觸摸事件向 Behavior 的引導。

layoutDependsOn + onDependentViewChanged + onDependentViewRemoved

 /** * child是否要依賴dependency * @param parent CoordinatorLayout * @param child 該Behavior對應的那個View * @param dependency 要檢查的View(child是否要依賴這個dependency) * @return true 依賴, false 不依賴 */ public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) { return false; } /** * 在layoutDependsOn返回true的基礎上之後,及時報告dependency的狀態變化 * @param parent CoordinatorLayout * @param child 該Behavior對應的那個View * @param dependency child依賴dependency * @return true 處理了, false 沒處理 */ public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) { return false; } /** * 在layoutDependsOn返回true的基礎上之後,報告dependency被移除了 * @param parent CoordinatorLayout * @param child 該Behavior對應的那個View * @param dependency child依賴dependency */ public void onDependentViewRemoved(CoordinatorLayout parent, V child, View dependency) { }

所有源頭都在 CoordinatorLayout 類裡面。先看 onAttachedToWindow:

 @Override public void onAttachedToWindow() { super.onAttachedToWindow(); resetTouchBehaviors(); if (mNeedsPreDrawListener) { if (mOnPreDrawListener == null) { mOnPreDrawListener = new OnPreDrawListener(); } final ViewTreeObserver vto = getViewTreeObserver(); vto.addOnPreDrawListener(mOnPreDrawListener); } if (mLastInsets == null && ViewCompat.getFitsSystemWindows(this)) { // We're set to fitSystemWindows but we haven't had any insets yet... // We should request a new dispatch of window insets ViewCompat.requestApplyInsets(this); } mIsAttachedToWindow = true; }

這裡給 ViewTreeObserver 添加了一個 OnPreDrawListener:

 class OnPreDrawListener implements ViewTreeObserver.OnPreDrawListener { @Override public boolean onPreDraw() { dispatchOnDependentViewChanged(false); return true; } }

onPreDraw 在每次 draw 時都會調用,也就是 CoordinatorLayout 每次重繪、View 狀態發生變化時都會觸發。重點就在 dispatchOnDependentViewChanged,參數 false 表示這不是嵌套滑動引起,而是 View 狀態改變引起:

 void dispatchOnDependentViewChanged(final boolean fromNestedScroll) { final int layoutDirection = ViewCompat.getLayoutDirection(this); final int childCount = mDependencySortedChildren.size(); for (int i = 0; i < childCount; i++) { final View child = mDependencySortedChildren.get(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Check child views before for anchor for (int j = 0; j < i; j++) { final View checkChild = mDependencySortedChildren.get(j); if (lp.mAnchorDirectChild == checkChild) { offsetChildToAnchor(child, layoutDirection); } } // Did it change? if not continue final Rect oldRect = mTempRect1; final Rect newRect = mTempRect2; getLastChildRect(child, oldRect); getChildRect(child, true, newRect); if (oldRect.equals(newRect)) { continue; } recordLastChildRect(child, newRect); // Update any behavior-dependent views for the change for (int j = i + 1; j < childCount; j++) { final View checkChild = mDependencySortedChildren.get(j); final LayoutParams checkLp = (LayoutParams) checkChild.getLayoutParams(); final Behavior b = checkLp.getBehavior(); if (b != null && b.layoutDependsOn(this, checkChild, child)) { if (!fromNestedScroll && checkLp.getChangedAfterNestedScroll()) { // If this is not from a nested scroll and we have already been changed // from a nested scroll, skip the dispatch and reset the flag checkLp.resetChangedAfterNestedScroll(); continue; } final boolean handled = b.onDependentViewChanged(this, checkChild, child); if (fromNestedScroll) { // If this is from a nested scroll, set the flag so that we may skip // any resulting onPreDraw dispatch (if needed) checkLp.setChangedAfterNestedScroll(handled); } } } } }

mDependencySortedChildren 存放的是 CoordinatorLayout 所有子 View,只不過把相關連的 View 放到了一起(關聯有兩種:XML 裡設置了 layout_anchor,或 Behavior 裡 layoutDependsOn 返回 true)。遍歷時,先找到設置了 layout_anchor 的 View 並調整位置,再找到 Behavior depend on child 的 View,調用 layoutDependsOn 判斷是否依賴,依賴則繼續調用 onDependentViewChanged。

還差 onDependentViewRemoved。它在構造函數裡通過 super.setOnHierarchyChangeListener 監聽 View 層次變化,當 View 被 remove 時會回調 onChildViewRemoved:

 final class HierarchyChangeListener implements OnHierarchyChangeListener { @Override public void onChildViewAdded(View parent, View child) { if (mOnHierarchyChangeListener != null) { mOnHierarchyChangeListener.onChildViewAdded(parent, child); } } @Override public void onChildViewRemoved(View parent, View child) { dispatchDependentViewRemoved(child); if (mOnHierarchyChangeListener != null) { mOnHierarchyChangeListener.onChildViewRemoved(parent, child); } } }

繼續看 dispatchDependentViewRemoved:

 void dispatchDependentViewRemoved(View removedChild) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final Behavior b = lp.getBehavior(); if (b != null && b.layoutDependsOn(this, child, removedChild)) { b.onDependentViewRemoved(this, child, removedChild); } } }

它找到對應 View 的 Behavior,只要是 layoutDependsOn 的就調用 onDependentViewRemoved。至此這三個函數的調用時機與順序就梳理清楚了。

嵌套滑動相關的一組函數

 /** * 有嵌套滑動到來了,問下該Behavior是否接受嵌套滑動 */ public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target, int nestedScrollAxes) { return false; } /** * Behavior接受了嵌套滑動的請求該函數調用,onStartNestedScroll返回true時被調用 */ public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target, int nestedScrollAxes) { // Do nothing } /** * 停止嵌套滑動 */ public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) { // Do nothing } /** * 嵌套滑動的子View在滑動之後報告過來的滑動情況 */ public void onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { // Do nothing } /** * 在嵌套滑動的子View滑動之前告訴過來的准備滑動的情況,consumed 由我們指定並回傳給子View */ public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed) { // Do nothing } /** * 嵌套滑動的子View在fling之後報告過來的fling情況 */ public boolean onNestedFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY, boolean consumed) { return false; } /** * 在嵌套滑動的子View未fling之前告訴過來的准備fling的情況 */ public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY) { return false; }

由於 CoordinatorLayout 實現了 NestedScrollingParent 接口,有嵌套滑動時會調用到它裡面的 onStartNestedScroll、onNestedScrollAccepted、onStopNestedScroll、onNestedScroll、onNestedPreScroll、onNestedFling、onNestedPreFling 這些函數,而它們做的事情大同小異,都是直接過渡給 Behavior 裡面對應的函數。

由此我們就清楚了:這一組函數的調用時機,正是有嵌套滑動發生的時候。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved