一、前言
NestedScrollView 机制是周三听其他组的同学分享才知道的。谈起技术分享,让我学习很多:
- 关于视野:学习这件事情,从来不是孤军奋战,应该多多交流和分析、讨论。正如爱尔兰作家说:你有一个苹果,我有一个苹果,我们交换一下,一人还是一个苹果;但是,你有一个思想,我有一个思想,我们交换一下,一人就有两个思想。交流的重要性。
- 关于表达:分享的同学表达能力很强,能清楚的明白参数方法的概念,这是需要基本功的。
- 关于技术进阶:技术的研究通常是建立在已知问题上的,技术是一种工具,不是为了技术而技术,应该是为了快乐而快乐。
关于NestedScrollView 的学习,想在前人的研究基础上,总结两篇文章,一篇文章讲基础应用,一篇简单的深入分析一下源码,所谓知其然,还要知其背后的思想。
本文的写作逻辑如下:
- 前言
- NestedScrollIng 相关类简介
- NestedScrollingChild 与 NestedScrollingParent 方法详解
- DEMO介绍
- 小结
二、NestedScrollIng 相关类简介
2.1、ScrollingView 上层滑动接口
继承该接口的类有:
该接口主要作用是:
An interface that can be implemented by Views to provide scroll related APIs.
2.2、NestedScrollView 嵌套滑动视图
传统的ScrollView 只是继承了帧布局,与该类相关的接口有 :
该类的作用是:
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.
不仅支持传统的 ScrollView功能,还可以支付嵌套的父View 与子View 的滑动,系统默认开启嵌套滑动支持。
2.3、NestedScrollingChild 子视图嵌套滑动接口
与该接口相关的类有 :
该接口的作用:
This interface should be implemented by View subclasses that wish to support dispatching nested scrolling operations to a cooperating parent ViewGroup.
Classes implementing this interface should create a final instance of a NestedScrollingChildHelper as a field and delegate any View methods to the NestedScrollingChildHelper methods of the same signature.
2.4、NestedScrollingParent 父视图嵌套滑动接口
与该接口相关的类有 :
该接口的作用:
This interface should be implemented by ViewGroup subclasses that wish to support scrolling operations delegated by a nested child view.
Classes implementing this interface should create a final instance of a NestedScrollingParentHelper as a field and delegate any View or ViewGroup methods to the NestedScrollingParentHelper methods of the same signature.
三、NestedScrollingChild 与 NestedScrollingParent 方法详解
官方NestedScrolling机制涉及关键的类(接口),有:
NestedScrollingChild
NestedScrollingParent
NestedScrollingChildHelper
NestedScrollingParentHelper
3.1、NestedScrollingChild相关方法解析
1、publiv void setNestedScrollingEnabled(boolean enabled);
NestedScrollingChild中的方法,设置该View是否开启Nested Scrolling机制,一个相关联方法为isNestedScrollingEnabled()
2、public boolean startNestedScroll(int axes);
在给定的方向(axes)上开始一个Nested Scroll,只有返回值是true的情况下才会执行之后的方法,否则NestedScrolling机制无效. 默认实现(NestedScrollingChildHelper中的实现)会找到该View的parent,调用parent的onStartNestedScroll方法,如果parent为null或者onStartNestedScroll()返回false,则流程结束.否则调用NestedScrollingParent.onNestedScrollAccepted给其一个初始化配置的机会.
3、public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow)
传统的事件分发机制有个onInterceptTouchEvent()方法来拦截事件,让ViewGroup可以优先于子View处理触摸事件,这个机制而Nested Scrolling机制也提供了类似的机制.这个机制的实现就是依靠dispatchNestedPreScroll方法.这个方法会在child消耗掉滑动事件之前调用,给parent一个率先处理滑动事件的机会.
offsetInWindow是自己本身的窗体变化,这个方法需要计算这个值做处理来修正touch事件的做标志。
4、public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, dyUnconsumed, int[] offsetInWindow)
分发ne