引言
CoordinatorLayout的使用核心就是Beahvior,使用Behavior来实现直接子控件之间的交互。(PS:直接子控件是指CoordinatorLayout的直接子控件)
参考文章:
1. Behavior
CoordinatorLayout.Behavior<T>,T是指这个Child,而不是dependency。Child是指这个CoordinatorLayout的子控件,dependency是指这个Child所依赖的View,即Child依赖于dependency的变化。
这是一个观察者模式的运用,Child向CoordinatorLayout注册一个回调,告知CoordinatorLayout在dependency发生变化时通知它,这样当dependency发生变化时,Child会得到这个通知。
看完上面两段话,可能有种一脸懵逼的感觉,下面我们利用一个例子来理解,你会瞬间有种豁然开朗的感觉。
效果图:
效果图
- 布局文件activity_test.xml
<?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.gjj.gd.materialdesign.activity.TestActivity">
<TextView
app:layout_behavior="com.gjj.gd.materialdesign.behavior.FollowBehavior"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="观察者"/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="被观察者"
android:layout_gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
上面的布局文件中TextView被指定了一个layout_behavior属性,下面我们看看这个属性值FollowBehavior的代码。
- 自定义的FollowBehavior
package com.gjj.gd.materialdesign.behavior;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by gaojuanjuan on 2018/2/8.
*/
public class FollowBehavior extends CoordinatorLayout.Behavior<TextView> {
public FollowBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, TextView child, View dependency) {
return dependency instanceof Button;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, TextView child, View dependency) {
child.setX(dependency.getX()+200);
child.setY(dependency.getY()+200);
return true;
}
}
- 自定义Behavior时,我们发现CoordinatorLayout.Behavior<T>中的T就是我们的观察者TextView,而我们重写方法layoutDependsOn的参数dependency就是我们的被观察者。我们可以把上面的第二段话,针对这个例子做一个翻译,TextVew(观察者)向CoordinatorLayout注册一个回调,告知CoordinatorLayout在Button(被观察者)发生变化时通知它,这样当Button(被观察者)发生变化时,TextVew(观察者)就会得到通知做出相应的变化(从上面的代码我们可以看出TextView(观察者)的变化在方法onDependentViewChanged中发生)。
- 在上面的代码中我们重写了父类的两个方法:
- layoutDependsOn():这个方法在对界面进行布局时至少会调用一次,用来确定本次交互行为中的被观察者,在上面的代码中,当dependency是Buttom类的实例时返回true,就可以让系统知道布局文件中的Buttom就是本次交互行为中的被观察者。
- onDependentViewChanged():当被观察者发生变化时,这个方法会被调用,参数中的child就是本次交互行为中的观察者,观察者可以在这个方法中对被观察者的变化做出响应,从而完成一次交互行为。
- TestActivity.java代码
@BindView(R.id.btn)
Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
setTitle("CoordinatorLayout");
mBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
v.setX(event.getRawX()-v.getWidth()/2);
v.setY(event.getRawY() - v.getHeight()/2);
}
return true;
}
});
}
通过上面的例子,我们掌握了通过给CoordinatorLayout的子view设置Behavior来实现交互行为,这个Behavior会拦截发生在这个View上的Touch事件、嵌套滚动等,不仅如此,Behavior还能拦截对与它绑定的View的测量及布局。关于嵌套滚动,我们会在后续文章中进行详细介绍。下面我们来深入了解一下Behavior是如何做到这一切的。
2. 拦截Touch事件
CoordinatorLayout的onInterceptTouchEvent()方法里会遍历所有直接子View,对于绑定了Behavior的直接子View调用Behavior的onInterceptTouchEvent方法,若这个方法返回true,那么后续本该由相应子View处理的Touch事件都会交由Behavior处理。
我们看看CoordinatorLayout的onInterceptTouchEvent方法和onTouchEvent事件:
onInterceptTouchEventd的源码
@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();
}
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
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;
}
我们可以看到这个两个方法做的事情并不多,其实都交给performIntercept去做处理了。
performaIntercept的源码
// 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.
// 是否拦截一切在它之后的交互
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;
}
3. 拦截测量及布局
CoordinatorLayout在onMeasure()方法中,会遍历所有直接子View,若该子View绑定了一个Behavior,就会调用Behavior的onMeasureChild()方法,若此方法返回true,那么CoordinatorLayout对该子View的测量就不会进行。这样一来,Behavior就成功接管了对View的测量。
同样,CoordinatorLayout在onLayout()方法中也做了与onMeasure()方法中相似的事,让Behavior能够接管对相关子View的布局。
接下来我们我们看看CoordinatorLayout的onMeasure和onLayout方法的源码:
onMeasure的源码
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//解析CoordinatorLayout所有子View的behavior
prepareChildren(true);
ensurePreDrawListener();
...
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
...
//获取子控件的behavior对象
final Behavior b = lp.getBehavior();
//进行子View的测量,我们可以看到在测量之前会调用b.onMeasureChild方法,如该方法返回true,
//那么behavior就会成功拦截CoordinatorLayout的测量了
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);
}
}
}
拦截布局和测量的原理其实是一样的。
网友评论