1、CoordinatorLayout的作用
在学习CoordinatorLayout之前,很有必要了解CoordinatorLayout能帮我们做什么。CoordinatorLayout就是帮我们协调子View的。怎么协调呢? 就是它根据我们的定制,帮助我们协调各个子View的布局。效果如下:
左边红色的矩形是我们一个自定义的可以跟随手指滑动的View,右边灰色矩形是一个Button。我们水平拖动红色矩形时,Button跟随其水平移动,竖直拖动红色矩形时,Button跟随其竖直移动。这个效果如果不用CoordinatorLayout去实现也可以,但是代码的耦合度应该非常大,代码必须要持有2个View的引用,然后在onTouchEvent里面做各种判断。如果我们想要实现更多的View要根据红色的View的移动相应作出响应,那么那就得在红色View的onTounchEvent里面针对其他的View处理各种逻辑。
2、CoordinatorLayout中如何控制两个View的移动关系
CoordinatorLayout的使用核心是Behavior,Behavior就是执行你定制的动作。在讲Behavior之前必须先理解两个概念:Child和Dependency,他们都是CoordinatorLayout的子View。Child是指要执行动作子View,而Dependency是Child依赖的View。Child根据Dependency的移动发生移动。比如上面的gif图中,红色的View就是Dependency,Button就是Child,Button的动作是依赖于红色的View。Child如何根据Dependency移动都是在Behavior中实现。
怎么使用Behavior呢,首先,我们定义一个类,继承CoordinatorLayout.Behavior<T>,其中,泛型参数T是我们要执行动作的View类,也就是Child。然后就是去实现Behavior的两个方法:
/**
* 判断child的布局是否依赖dependency。返回false表示child不依赖dependency,ture表示依赖
*/
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, T child, View dependency) {
boolean rs;
//根据逻辑判断rs的取值
return rs;
}
/**
* 当dependency发生改变时(位置、宽高等),执行这个函数
* 返回true表示child的位置或者是宽高要发生改变,否则就返回false
*/
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, T child, View dependency) {
//child要执行的具体动作
return true;
}
3、如何使用
1)、根布局使用CoordinatorLayout,CoordinatorLayout是一个ViewGroup,其下放两个子View。布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.study.androidother.DesignSupportLibrary.CoordinatorLayout.CoordinatorLayoutTestActivity">
<Button
android:id="@+id/btn"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="button"
app:layout_behavior="com.study.androidother.DesignSupportLibrary.CoordinatorLayout.CoordinatorLayoutBehavior"/>
<com.study.androidother.DesignSupportLibrary.CoordinatorLayout.view.MoveView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/red" />
</android.support.design.widget.CoordinatorLayout>
2)实现Behavior
public class CoordinatorLayoutBehavior extends CoordinatorLayout.Behavior {
private String TAG = CoordinatorLayoutBehavior.class.getSimpleName();
public CoordinatorLayoutBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 判断child的布局是否依赖dependency
* 返回false表示child不依赖dependency,ture表示依赖
*/
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof MoveView;
}
/**
* 当dependency发生改变时(位置、宽高等),执行这个函数
* 返回true表示child的位置或者是宽高要发生改变,否则就返回false
*/
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
int left = dependency.getLeft() + 350;
int top = dependency.getTop();
// 在有的版本中不起效果
// child.layout(left, top, right, bottom);
child.setX(left);
child.setY(top);
return true;
}
}
4、为什么Behavior可以拦截一切?
我们知道ViewGroup的测量,布局,事件分发都是需要自己处理的,那么CoordinatorLayout究竟给了Behavior什么特权,让它能够让它拦截一切?
因为CoordinatorLayout在onMeasure()、onLayout()、onInterceptTouchEvent()、onTouchEvent()中都先执行Behavior的onMeasure()、onLayout()、onInterceptTouchEvent()、onTouchEvent()。
onMeasure直接备注在源码里了。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//之前已经提到过了 解析Behavior,并按依赖顺序重排子View顺序
prepareChildren();
//用于addPreDrawListener,OnPreDrawListener里会调用 dispatchOnDependentViewChanged(false)
ensurePreDrawListener();
//...
// 计算 padding width height 处理 fitSystemWindow等
//...
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int keylineWidthUsed = 0;
//...处理keyline childWidthMeasureSpec等
final Behavior b = lp.getBehavior();
// 跟onMeasure相同,当behavior的onMeasureChild方法返回true的时候,我们就可以拦截CoordinatorLayout默认的measure
if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0)) {
onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0);
}
//...
}
//...
final int width = ViewCompat.resolveSizeAndState(widthUsed, widthMeasureSpec,
childState & ViewCompat.MEASURED_STATE_MASK);
final int height = ViewCompat.resolveSizeAndState(heightUsed, heightMeasureSpec,
childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT);
setMeasuredDimension(width, height);
}
onLayout
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int layoutDirection = ViewCompat.getLayoutDirection(this);
//mDependencySortedChildren 在 onMeasure里已经排过序了
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior behavior = lp.getBehavior();
//可以看到,当behavior.onLayoutChild()返回true的时候,就可以拦截掉CoordinatorLayout的默认Layout操作!
if (behavior == null || !behavior.onLayoutChild(this, child, layoutDirection)) {
onLayoutChild(child, layoutDirection);
}
}
}
在处理touch事件中,CoordinatorLayout重写了onInterceptTouchEvent
和onTouchEvent
,另外,它们都调用了CoordinatorLayout里定义的一个处理拦截的方法,performIntercept
(关键代码都在这方法之中),就看一下它们的实现吧。
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) {
//down的时候,跟大部分ViewGroup一样,需要重置一些状态以及变量,比如 mBehaviorTouchView
resetTouchBehaviors();
}
//这里看performIntercept TYPE_ON_INTERCEPT标记是 onInterceptTouchEvent
final boolean intercepted = performIntercept(ev, TYPE_ON_INTERCEPT);
if (cancelEvent != null) {
cancelEvent.recycle();
}
//当事件为UP和Cancel的时候去重置(同down)
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
resetTouchBehaviors();
}
return intercepted;
}
onTouchEvent
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean handled = false;
boolean cancelSuper = false;
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
// mBehaviorTouchView不为null(代表之前有behavior处理了down事件) 或者 performIntercept返回true 那么事件就交给mBehaviorTouchView
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) {
// 交给 behavior去处理事件
handled = b.onTouchEvent(this, mBehaviorTouchView, ev);
}
}
// Keep the super implementation correct
// 省略调用默认实现 up&cancel的时候重置状态
//...
return handled;
}
可以看到,其实这两个方法做的事情并不多,其实都交给performIntercept
方法去做处理了!
performIntercept
的实现如下:
// type 标记是intercept还是touch
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;
//按Z轴排序 原因很简单 让最上面的View先处理事件
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();
//当前事件已经被某个behavior拦截了(or newBlock),并且事件不为down,那么就发送一个 取消事件 给所有在拦截的behavior之后的behavior
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 是否要处理该事件
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处理了当前的事件,那么把它赋值给mBehaviorTouchView,它其实跟ViewGroup源码中的mFirstTouchTarget作用是一样的
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.
// 是否拦截一切在它之后的交互 好暴力-0-
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;
}
CoordinatorLayout在关键的方法里把处理权优先交给了Behavior,所以才让Behavior拥有了拦截一切的能力。
结语:
CoordinatorLayout的原理请看文章