CoordinatorLayout三板斧第一式:依葫芦画瓢
主要作用:根据官方文档的解释,CoordinatoryLayout可以理解成一个超强功能的FramenLayout,CoordinatoryLayout主要有两种用法 1.作为app顶层布局的装饰或者镀铬。2.作为与一个或多个子视图进行特定交互的容器。
关于CoordinatorLayout的基本使用在这一片博客已经写得很清楚了我也是参考学习这位大佬的https://www.jianshu.com/p/5e6f2ae1d2ec
CoordinatorLayout三板斧第二式:深入理解嵌套滑动
嵌套滑动有两个非常关键的接口:NestedScrollingParent,NestedScrollingChild。
通过查看源码我们知道:NestedScrollingParent :由希望支持嵌套子视图委派的滚动操作的ViewGroup子类实现。
NestedScrollingChild :由希望支持将嵌套滚动操作分派给协作父ViewGroup的View子类实现
view的嵌套滑动由几个关键方法来实现:
- boolean startNestedScroll()开始进行嵌套滑动,如果返回ture意味着找到可以进行嵌套滑动的父容器,false表示不需要进行嵌套滑动。
- void stopNestedScroll()停止嵌套滑动
- boolean dispatchNestedPreScroll() 在内层view处理滚动事件前先被调用,可以让外层view先消耗部分滚动
- boolean dispatchNestedScroll() 在内层view将剩下的滚动消耗完之后调用,可以在这里处理最后剩下的滚动
- onNestedPreFling 在内层view的Fling事件处理之前被调用
- onNestedFling 在内层view的Fling事件处理完之后调用
同样的对于NestedScrollingParent有着相对应的方法
- boolean onStartNestedScroll()开始进行嵌套滑动,如果返回false后面的一些列嵌套滑动事件都不会再被接收。
- onStopNestedScroll()停止嵌套滑动。
- onNestedPreScroll()与dispatchNestedPreScroll()对应。
- onNestedScroll()与dispatchNestedScroll对应。
嵌套滑动源码分析:以RecyclerView和CoordinatorLayout为例:
当RecyclerView开始处理这一次触摸事件:RecyclerView的onTouchEvent会被调用。
@Override
public boolean onTouchEvent(MotionEvent e) {
省略部分代码
switch (action) {
case MotionEvent.ACTION_DOWN: {
省略部分代码
startNestedScroll(nestedScrollAxis, TYPE_TOUCH);
} break;
省略部分带
return true;
}
可以看到在action_down的时候调用了startNestedScroll()方法,而startNestedScroll最终调用了NestedScrollingChildHelper的startNestedScroll()方法。他的实现如下:
public boolean startNestedScroll(@ScrollAxis int axes, @NestedScrollType int type) {
if (hasNestedScrollingParent(type)) {
// Already in progress
return true;
}
if (isNestedScrollingEnabled()) {
ViewParent p = mView.getParent();
View child = mView;
while (p != null) {
if (ViewParentCompat.onStartNestedScroll(p, child, mView, axes, type)) {
setNestedScrollingParentForType(type, p);
ViewParentCompat.onNestedScrollAccepted(p, child, mView, axes, type);
return true;
}
if (p instanceof View) {
child = (View) p;
}
p = p.getParent();
}
}
return false;
}
其核心就是:不断循环通过ViewParentCompat的onStartNestedScroll()方法判断当前parent是否接受嵌套滑动,如果某个parent返回ture,设置记录本次嵌套滑动消费的parent,在调用ViewParentCompat的onNestedScrollAccepted()方法。ViewParentCompat的onStartNestedScroll()实现如下:
public static boolean onStartNestedScroll(ViewParent parent, View child, View target,
int nestedScrollAxes, int type) {
if (parent instanceof NestedScrollingParent2) {
// First try the NestedScrollingParent2 API
return ((NestedScrollingParent2) parent).onStartNestedScroll(child, target,
nestedScrollAxes, type);
} else if (type == ViewCompat.TYPE_TOUCH) {
// Else if the type is the default (touch), try the NestedScrollingParent API
return IMPL.onStartNestedScroll(parent, child, target, nestedScrollAxes);
}
return false;
}
可以看到它是根据paren的实现不同接口来进行不同的处理的,我这里查看的源代码是v4:27.1.1