Android 進階——高級UI必知必會之CoordinatorLayout源碼解析及Behavior解耦思想分享(九)

引言

前面一篇文章Android進階——Material Design新控件之利用CoordinatorLayout協同多控件交互(七)介紹了下CoordinatorLayout 的簡單應用,在使用的時候,你是否有想過爲何CoordinatorLayout比其他ViewGroup具有可以讓直接子View交互的功能?相關係列文章鏈接如下:

一、CoordinatorLayout核心角色

CoordinatorLayout直接繼承自ViewGroup並且實現了NestedScrollingParent2接口,核心參與角色主要有:CoordinatorLayout.CoordinatorLayout.LayoutParamsCoordinatorLayout.Behavior兩個內部類。

NestedScrollingParent2接口主要是用於處理嵌套滑動事件的,本質上也沒有什麼特別的邏輯,和Behavior一樣是預約定好的接口API,區別在於Behavior是由CoordinatorLayout賦能,而NestedScrollingParent2是由實現此接口的View進行賦能。

1、CoordinatorLayout.LayoutParams

CoordinatorLayout.LayoutParams是CoordinatorLayout的內部類,和其他ViewGroup功能類似,在CoordinatorLayout的generateLayoutParams方法中直接調用構造方法進行初始化且在CoordinatorLayout.LayoutParams構造方法內部調用CoordinatorLayout的parseBehavior根據配置的Behavior的類名反射創建Behavior並賦值到mBehavior字段,然後再通過Behavior的onAttachedToLayoutParams方法Called when the Behavior has been attached to a LayoutParams instance.,所以除了保存CoordinatorLayout內的子控件的佈局信息之外,還保存着對應的Behavior對象引用 mBehavior

public class CoordinatorLayout extends ViewGroup implements NestedScrollingParent2 {
   ...
   public static class LayoutParams extends MarginLayoutParams {
   		...
        Behavior mBehavior;
        
		LayoutParams(@NonNull Context context, @Nullable AttributeSet attrs) {
		    super(context, attrs);
		    final TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CoordinatorLayout_Layout);
		    this.gravity = a.getInteger(R.styleable.CoordinatorLayout_Layout_android_layout_gravity,Gravity.NO_GRAVITY);
		    mAnchorId = a.getResourceId(R.styleable.CoordinatorLayout_Layout_layout_anchor,View.NO_ID);
		    this.anchorGravity = a.getInteger(R.styleable.CoordinatorLayout_Layout_layout_anchorGravity,Gravity.NO_GRAVITY);
		    this.keyline = a.getInteger(R.styleable.CoordinatorLayout_Layout_layout_keyline,-1);
		
		    insetEdge = a.getInt(R.styleable.CoordinatorLayout_Layout_layout_insetEdge, 0);
		    dodgeInsetEdges = a.getInt(R.styleable.CoordinatorLayout_Layout_layout_dodgeInsetEdges, 0);
		    mBehaviorResolved = a.hasValue(R.styleable.CoordinatorLayout_Layout_layout_behavior);
		    if (mBehaviorResolved) {
		        mBehavior = parseBehavior(context, attrs, a.getString(R.styleable.CoordinatorLayout_Layout_layout_behavior));
		    }
		    a.recycle();
		    if (mBehavior != null) {
		        // If we have a Behavior, dispatch that it has been attached
		        mBehavior.onAttachedToLayoutParams(this);
		    }
		}
    }
    ...
}

這個類設計的原因是在於我們要在XML中通過自定義的屬性給主題View綁定對應的Behavior,所以需要重寫generateLayoutParams方法傳入自定義的屬性。

2、CoordinatorLayout.Behavior

CoordinatorLayout.Behavior是CoordinatorLayout的抽象泛型內部類,Behvaior 本身並不具備具體的業務功能,本質上就只是爲了進行解耦的而封裝的一個交互接口集合類,而CoordinatorLayout可以藉助Behavior使得獨立的子View可以產生交互,是因爲CoordinatorLayout內部把事件分發至Behavior,讓Behavior具有可以控制其他子View的效果了,也是CoordinatorLayout中核心的設計,也正是因爲這個CoordinatorLayout.Behavior使得CoordinatorLayout中的直接子控件間可以產生聯繫,CoordinatorLayout.Behavior可以理解爲事件分發的傳送渠道(並不負責具體的任務),只是負責調用對應子View的相關方法parseBehavior方法根據配置的Behavior的類名反射創建Behavior並賦值到mBehavior字段,這是繼承Behavior時必須要重寫兩個參數的構造方法的原因。通俗來說,Behavior 設置在誰身上,就可以通過Behavior來改變它對應的狀態,觀察者改變時,主題也跟着改變

2、CoordinatorLayout.Behavior核心方法

CoordinatorLayout.Behavior中最核心的方法只有三個:layoutDependsOn方法、onDependentViewChanged方法和onDependentViewRemoved方法,通過這三個方法就可以實現直接子View之間的交互,至於其他方法是處理到其他業務情況的時候,比如說嵌套滑動、重新佈局等等。

2.1、layoutDependsOn方法

當進行Layout請求的時候就會觸發執行,給CoordinatorLayout中的直接子控件設置了對應的Behavior之後,繪製時至少會執行一次,表示是否給配置了Behavior 的CoordinatorLayout直接子View 指定一個作爲觀察者角色的子View,返回true則表示主題角色child view的觀察者是dependency view, 當觀察者角色View狀態(大小、位置)發生變化時,不管被觀察View 的順序怎樣,被觀察的View也可監聽到並回調對應的方法;反之則兩者之間沒有建立聯繫。簡而言之,這個方法的作用是配置了Behavior的主題子控件被符合哪些條件邏輯的子控件觀察的(即作爲主題的觀察者之一)(Determine whether the supplied child view has another specific sibling view as a layout dependency)。

@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
    //TODO 在這裏自己去實現依賴聯繫成立的邏輯,允許建立則返回true,完全不依賴CoordinatorLayout,實現解耦
    if(dependency instanceof Button){
        return true;
    }
    return super.layoutDependsOn(parent, child, dependency);
}

2.2、onDependentViewChanged方法

當且僅當Dependency View 狀態(位置、大小等)改變時就會觸發,返回true則表示Behavior改變了主題的狀態,可能會執行多次,當然第一次繪製到佈局上也算是狀態改變時,所以自然也會觸發,至於當監聽到改變之後,如何去實現什麼樣的效果則由我們自己去開發實現。

/**
 * 當被觀察者的View 狀態(如:位置、大小)發生變化時就會觸發執行
 * @return true if the Behavior changed the child view's size or position, false otherwise
 */
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
	//TODO 根據具體的業務需求定義我們的結果
    return super.onDependentViewChanged(parent, child, dependency);
}

2.3、onDependentViewRemoved方法

當依賴的Dependency View被移除時觸發回調(Respond to a child’s dependent view being removed.)

/**
 * Respond to a child's dependent view being removed.
 * @param parent the parent view of the given child
 * @param child the child view to manipulate
 * @param dependency the dependent view that has been removed
 */
public void onDependentViewRemoved(@NonNull CoordinatorLayout parent, @NonNull V child,
        @NonNull View dependency) {
}

2.4、onInterceptTouchEvent方法設置是否攔截觸摸事件

設置是否攔截觸摸事件,返回true則表示當前Behavior會攔截觸摸事件,不會分發到CoordinatorLayout內的子View下了。

public boolean onInterceptTouchEvent(@NonNull CoordinatorLayout parent, @NonNull V child,
       @NonNull MotionEvent ev) {
   return false;
}

2.5、onTouchEvent方法處理觸摸事件

public boolean onTouchEvent(@NonNull CoordinatorLayout parent, @NonNull V child,
       @NonNull MotionEvent ev) {
   return false;
}

2.6、onMeasureChild方法測量使用Behavior的View尺寸

/**
 * Called when the parent CoordinatorLayout is about to measure the given child view.
 * @param child the child to measure
 * @return true if the Behavior measured the child view, false if the CoordinatorLayout
 *         should perform its default measurement
 */
public boolean onMeasureChild(@NonNull CoordinatorLayout parent, @NonNull V child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    return false;
}

2.7、onLayoutChild方法重新佈局使用Behavior的View

/**
 * Called when the parent CoordinatorLayout is about the lay out the given child view.
 * @return true if the Behavior performed layout of the child view, false to request default layout behavior
 */
public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull V child,
        int layoutDirection) {
    return false;
}

xxNestedxxScrollxx方法是用於監聽嵌套滑動的事件,對應的是NestedScrollingParent2接口裏的相關方法。

2.8、onStartNestedScroll方法

當CoordinatorLayout 的子View試圖開始進行嵌套滑動的時候觸發,返回true時表示CoordinatorLayout充當nested scroll parent 處理這次滑動,當且僅當返回true時,當前Behavior才能收到後面的一些nested scroll事件回調(如:onNestedPreScroll、onNestedScroll等)。

/**
 * @param coordinatorLayout 和Behavior 綁定的View的父CoordinatorLayout
 * @param child  和Behavior 綁定的View  觀察者
 * @param directTargetChild
 * @param target
 * @param nestedScrollAxes 嵌套滑動滑動方向
 * @param type the type of input which cause this scroll event
 * @return true if the Behavior wishes to accept this nested scroll
 */
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild,
                                   View target, int nestedScrollAxes, int type) {
    return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes,type);
}

2.9、onNestedScroll方法

嵌套滑動進行中且onStartNestedScroll方法返回true時回調,當子View調用dispatchNestedPreScroll方法時會調用該方法

/**
 * 進行嵌套滾動時被調用
 * @param coordinatorLayout
 * @param child
 * @param target
 * @param dxConsumed target 已經消費的x方向的距離
 * @param dyConsumed target 已經消費的y方向的距離
 * @param dxUnconsumed x 方向剩下的滾動距離
 * @param dyUnconsumed y 方向剩下的滾動距離即未消費的距離
 */
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dxConsumed,
                           int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
    super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,type);
}

在這裏插入圖片描述

2.10、onNestedPreScroll方法

onStartNestedScroll方法返回true且嵌套滑動進行前,要監聽的子 View將要滑動,滑動事件即將被消費(但最終被誰消費,可以通過代碼控制)

/**
 * 嵌套滾動發生之前被調用,nested scroll child 消費掉自己的滾動距離之前,嵌套滾動每次被nested scroll child
 * 更新都會調用onNestedPreScroll。
 * @param coordinatorLayout
 * @param child
 * @param target
 * @param dx  用戶水平方向的滾動距離
 * @param dy  用戶豎直方向的滾動距離
 * @param consumed 可以修改這個數組表示你消費了多少距離,假設用戶滑動了100px,child 做了90px 的位移,你需要把 consumed[1]的值改成90,這樣CoordinatorLayout就能知道只處理剩下的10px的滾動。
 */
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed, int type) {
    super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed,type);
}

2.11、onNestedFling方法

用戶鬆開手指後會進行慣性滑動時調用,參數提供了速度信息,可以根據這些速度信息決定最終狀態。

        /**
         * Called when a nested scrolling child is starting a fling or an action that would
         * be a fling.
         * @param velocityX horizontal velocity of the attempted fling
         * @param velocityY vertical velocity of the attempted fling
         * @param consumed true if the nested child view consumed the fling
         * @return true if the Behavior consumed the fling
         *
         * @see NestedScrollingParent#onNestedFling(View, float, float, boolean)
         */
        public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout,
                @NonNull V child, @NonNull View target, float velocityX, float velocityY,
                boolean consumed) {
            return false;
        }

2.12、onNestedPreFling方法

用戶鬆開手指後會發生慣性動作之前調用,參數提供了速度信息,可以根據這些速度信息決定最終狀態,比如滾動Header,是讓Header處於展開狀態還是摺疊狀態,返回true 則表示消費了fling.

    /**
     * 
     *
     * @param coordinatorLayout
     * @param child
     * @param target
     * @param velocityX x 方向的速度
     * @param velocityY y 方向的速度
     * @return
     */
    @Override
    public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, View child, View target,
                                    float velocityX, float velocityY) {
        return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY);
    }

2.13、onStopNestedScroll方法

在嵌套滑動結束(ACTION_UP或ACTION_CANCEL)時觸發。

/**
 *  嵌套滾動結束時被調用,這是一個清除滾動狀態等的好時機。
 * @param coordinatorLayout
 * @param child
 * @param target
 */
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, int type) {
    super.onStopNestedScroll(coordinatorLayout, child, target,type);
}

簡單來說,拋開CoordinatorLayout 這個Behavior裏的所有方法都沒有任務具體的功能,是CoordinatorLayout爲了解耦,抽象了一層接口並封裝爲Behavior,當CoordinatorLayout裏進行事件分發時主動去調用Behavior的接口即賦能。

Behavior機制適用於同一Parent ViewGroup下相互獨立的子View之間進行交互,如果View之間已經存在引用聯繫則沒有必要去使用Behavior增加複雜度了。

二、CoordinatorLayout的核心流程解析

CoordinatorLayout本質上就是ViewGroup+Behavior 模型搭建爲變形的“觀察者模式”觀察者View和主題View都隸屬於CoordinatorLayout直接子View通過在佈局中給控件配置app:layout_behavior屬性來指定主題角色,再在這個Behavior 中的layoutDependsOn方法給主題尋找對應的觀察者角色,這樣就建立了聯繫,當觀察者的位置、大小等狀態改變時,主題也可監聽到並回調Behavior裏的方法。

1、在CoordinatorLayout的generateLayoutParams方法中完成CoordinatorLayout.LayoutParams的實例化

generateLayoutParams方法的作用是定義父View下所有子View所使用的LayoutParams類,只要重寫了generateLayoutParams方法,所有子View就一定會使用重寫的LayoutParams來修飾自己,比如說你自定ViewGroup時需要把自定義的屬性傳入,就需要重寫這個方法。

@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
}

2、在CoordinatorLayout.LayoutParams構造方法中parseBehavior解析AttributeSet得到Behavior對應的類名

static final Class<?>[] CONSTRUCTOR_PARAMS = new Class<?>[] {
         Context.class,
         AttributeSet.class
 };

static Behavior parseBehavior(Context context, AttributeSet attrs, String name) {
     if (TextUtils.isEmpty(name)) {
         return null;
     }
     final String fullName;
     if (name.startsWith(".")) {
         fullName = context.getPackageName() + name;
     } else if (name.indexOf('.') >= 0) {
         fullName = name;
     } else {
         fullName = !TextUtils.isEmpty(WIDGET_PACKAGE_NAME)? (WIDGET_PACKAGE_NAME + '.' + name): name;
     }
     try {
     	 
         Map<String, Constructor<Behavior>> constructors = sConstructors.get();
         if (constructors == null) {
             constructors = new HashMap<>();
             sConstructors.set(constructors);
         }
         Constructor<Behavior> c = constructors.get(fullName);
         if (c == null) {
             final Class<Behavior> clazz = (Class<Behavior>) context.getClassLoader().loadClass(fullName);
		     ///這是繼承Behavior時必須要重寫兩個參數的構造方法的原因
             c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
             c.setAccessible(true);
             ///把構造方法緩存起來
             constructors.put(fullName, c);
         }
         return c.newInstance(context, attrs);
     } catch (Exception e) {
         throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e);
     }
 }

3、CoordinatorLayout 處理事件分發時給Behavior對應的方法賦能

Android事件分發主要是通過dispatchTouchEventonInterceptTouchEventonTouchEvent三個方法協同完成的,而CoordinatorLayout中沒有重寫dispatchTouchEvent方法說明使用的是其父類的邏輯並不是CoordinatorLayout所特有的,我們就把CoordinatorLayout的onInterceptTouchEvent方法當成事件分發的起點開始分析,當接收到DOWN或者UP或CANCEL事件時,遍歷子View查找對應的Behavior並調用其對應的onInterceptTouchEvent或onTouchEvent方法並把返回值設置到CoordinatorLayout的onInterceptTouchEvent方法的返回值

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    final int action = ev.getActionMasked();

    // Make sure we reset in case we had missed a previous important event.
    if (action == MotionEvent.ACTION_DOWN) {
//接收到DOWN事件時,遍歷調用Behavior的調用onInterceptTouchEvent方法後回收事件,重置設置爲false即讓關聯的Behavior可以與子View交互,true則阻止先前的交互
        resetTouchBehaviors(true);
    }
//判斷是否攔截,到這一步才賦予Behavior裏的onInterceptTouchEvent真正的攔截能力
    final boolean intercepted = performIntercept(ev, TYPE_ON_INTERCEPT);
    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
        resetTouchBehaviors(true);
    }
    return intercepted;
}

resetTouchBehaviors方法核心作用是觸發Behavior中onInterceptTouchEvent或者onTouchEvent方法

    private void resetTouchBehaviors(boolean notifyOnInterceptTouchEvent) {
        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) {
                final long now = SystemClock.uptimeMillis();
                final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                if (notifyOnInterceptTouchEvent) {
					//調用Behavior的onInterceptTouchEvent方法,而CoordinatorLayout.Behavior中的默認實現爲return false,僅僅是觸發了Behavior裏對應的回調而已
                    b.onInterceptTouchEvent(this, child, cancelEvent);
                } else {
                    b.onTouchEvent(this, child, cancelEvent);
                }
                cancelEvent.recycle();
            }
        }

        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            lp.resetTouchBehaviorTracking();
        }
        mBehaviorTouchView = null;
        mDisallowInterceptReset = false;
    }

performIntercept方法核心作用是遍歷子View找出對應的Behavior並得到onInterceptTouchEvent或onTouchEvent返回值,最後賦值到CoordinatorLayout的onInterceptTouchEvent中,相當於是給Behavior的onInterceptTouchEvent或onTouchEvent方法賦能,攔截或者不攔截事件。


	private boolean performIntercept(MotionEvent ev, final int type) {
        boolean intercepted = false;
        boolean newBlock = false;
        MotionEvent cancelEvent = null;
        final int action = ev.getActionMasked();
        final List<View> topmostChildList = mTempList1;
		//用當前的子視圖填充列表,並對其進行排序,以使z順序中的最高視圖位於列表的前面。
        getTopSortedChildren(topmostChildList);
        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;
            }
			//第一次執行時Behavior不爲空且intercepted未false時
            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;
                }
                //設置了Behavior的View 賦值給mBehaviorTouchView 
                if (intercepted) {
                    mBehaviorTouchView = child;
                }
            }
			...
        }
        topmostChildList.clear();
        return intercepted;
    }

然後,接着CoordinatorLayout的onTouchEvent方法被執行,如果不滿足條件則繼續往下分發,滿足條件則調用主題View中的Behavior。

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean handled = false;
        boolean cancelSuper = false;
        MotionEvent cancelEvent = null;
        final int action = ev.getActionMasked();
		//mBehaviorTouchView 是當Behavior對應方法返回true時在performIntercept方法裏被賦值的,是設置了Behavior的View
        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 (cancelEvent != null) {
            cancelEvent.recycle();
        }
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            resetTouchBehaviors(false);
        }
        return handled;
    }

4、在CoordinatorLayout的onMeasure方法遍歷查找子View並建立“主題——觀察者”聯繫

onMeasure方法遍歷查找子View,只是遍歷了直接子View沒有進行遞歸操作,所以這也是爲什麼僅支持直接子View去交互的原因。

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        prepareChildren();
        ensurePreDrawListener();
		...
        final int paddingLeft = getPaddingLeft();
        final int layoutDirection = ViewCompat.getLayoutDirection(this);
        final boolean isRtl = layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL;
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        final int childCount = mDependencySortedChildren.size();
        for (int i = 0; i < childCount; i++) {
            final View child = mDependencySortedChildren.get(i);
			///Visibility爲GONE時,是不能建立聯繫的
            if (child.getVisibility() == GONE) {
                continue;
            }
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();

            int keylineWidthUsed = 0;
			...
			//獲取Behavior
            final Behavior b = lp.getBehavior();
			//執行Behavior的onMeasureChild方法
            if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
                    childHeightMeasureSpec, 0)) {
                onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
                        childHeightMeasureSpec, 0);
            }
        }
		...
        setMeasuredDimension(width, height);
    }

prepareChildren方法添加子View時,獲取對應的Behavior並執行layoutDependsOn方法

    private void prepareChildren() {
        mDependencySortedChildren.clear();
        mChildDag.clear();
        for (int i = 0, count = getChildCount(); i < count; i++) {
            final View view = getChildAt(i);

            final LayoutParams lp = getResolvedLayoutParams(view);
            lp.findAnchorView(this, view);
            mChildDag.addNode(view);
            // Now iterate again over the other children, adding any dependencies to the graph
            for (int j = 0; j < count; j++) {
                if (j == i) {
                    continue;
                }
                final View other = getChildAt(j);
				// 查找View和other之間是否存在聯繫
                if (lp.dependsOn(this, view, other)) {
					//添加到mChildDag下對應的節點
                    if (!mChildDag.contains(other)) {
                        mChildDag.addNode(other);
                    }
                    mChildDag.addEdge(other, view);
                }
            }
        }
        // Finally add the sorted graph list to our list
        mDependencySortedChildren.addAll(mChildDag.getSortedList());
		...
    }

CoordinatorLayout的dependsOn方法真正去調用Behavior的layoutDependsOn方法

boolean dependsOn(CoordinatorLayout parent, View child, View dependency) {
    return dependency == mAnchorDirectChild
            || shouldDodge(dependency, ViewCompat.getLayoutDirection(parent))
            || (mBehavior != null && mBehavior.layoutDependsOn(parent, child, dependency));
}

5、CoordinatorLayout的onChildViewsChanged

當CoordinatorLayout的子View位置改變時,會主動觸發onChildViewsChanged方法,最終實現通過調用Behavior的onDependentViewChanged方法通知,其他Behavior方法賦能方式也類似。

final void onChildViewsChanged(@DispatchChangeEvent final int type) {
        final int layoutDirection = ViewCompat.getLayoutDirection(this);
        final int childCount = mDependencySortedChildren.size();
        final Rect inset = acquireTempRect();

        for (int i = 0; i < childCount; i++) {
			
            final View child = mDependencySortedChildren.get(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            if (type == EVENT_PRE_DRAW && child.getVisibility() == View.GONE) {
                // Do not try to update GONE child views in pre draw updates.
                continue;
            }

            // Check child views before for anchor
            for (int j = 0; j < i; j++) {
				//從前面集合中拿到觀察者View
                final View checkChild = mDependencySortedChildren.get(j);

                if (lp.mAnchorDirectChild == checkChild) {
                    offsetChildToAnchor(child, layoutDirection);
                }
            }
			...
            // 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 (type == EVENT_PRE_DRAW && checkLp.getChangedAfterNestedScroll()) {
                        // If this is from a pre-draw and we have already been changed from a nested scroll, skip the dispatch and reset the flag
                        checkLp.resetChangedAfterNestedScroll();
                        continue;
                    }

                    final boolean handled;
                    switch (type) {
                        case EVENT_VIEW_REMOVED:
                            // EVENT_VIEW_REMOVED means that we need to dispatch
                            // onDependentViewRemoved() instead
                            b.onDependentViewRemoved(this, checkChild, child);
                            handled = true;
                            break;
                        default:
                            // Otherwise we dispatch onDependentViewChanged()
                            handled = b.onDependentViewChanged(this, checkChild, child);
                            break;
                    }
                }
            }
        }
		...
    }

CoordinatorLayout負責監聽子View之間狀態變化並及時通知Behavior,使得監聽和監聽之後的處理解耦,CoordinatorLayout只負責告知你觀察者改變了,你主題View想要做何改變,就在Behavior對應的方法實現,以上就是CoordinatorLayout核心流程,僅供參考。

源碼版本Android 28

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章