NestedScrollingChild接口来源

1.事件分发介绍
2.Down、up事件的分发过程
3.onTouchListener、onClickListener调用时机
4.事件拦截应用
5.NestedScrollingParent
6.Behavior的使用
7.NestedScrollingChild接口来源
讲完上面的NestedScrollingParent接口后,你会发现在Vew、ViewGroup也有相似的身影。

View类的方法

NestedScrollingChild接口

由此可以看出二者的方法时基本一致的,NestedScrollingChild接口只有方法,而View的接口里还有方法体。并且和NestedScrollingChildHelper中的方法基本一致,以下是二者dispatchNestedScroll()方法。
NestedScrollingChildHelper

View

我们可以看出,二者基本是相似的。因此我推测最早开始这些方法都是在View中写的,但是后来把这些方法抽象成了接口,并将方法提取成Helper类。
因此查看了下源码,ViewGroup的onNestedScroll方法是在api21增加的,NestedScrollingParent、NestedScrollingParentHelper接口是在api22.1新增,而NestedScrollingParent2则是在api26.1新增。
ViewGroup中的方法与NestedScrollingParent中的接口一致。
但是又一处是不太一样的,在NestedScrollingChildhelper中调用onNestedPreScroll()方法时使用的是ViewParentCompat.onNestedScroll(),而在View中调用 mNestedScrollingParent.onNestedScroll(),即ViewGroup中的方法。

 public static void onNestedScroll(ViewParent parent, View target, int dxConsumed,
            int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
        if (parent instanceof NestedScrollingParent2) {
            // First try the NestedScrollingParent2 API
            ((NestedScrollingParent2) parent).onNestedScroll(target, dxConsumed, dyConsumed,
                    dxUnconsumed, dyUnconsumed, type);
        } else if (type == ViewCompat.TYPE_TOUCH) {
            // Else if the type is the default (touch), try the NestedScrollingParent API
            IMPL.onNestedScroll(parent, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
        }
    }

若父view实现的NestedScrollingParent2接口,则调用之,其他则调用父View实现的其他onNestedScroll接口。其中NestedScrollingParent2接口较NestedScrollingParent接口增加了一个参数NestedScrollType。

boolean onStartNestedScroll(@NonNull View child, @NonNull View target, @ScrollAxis int axes,
            @NestedScrollType int type);

改参数取值为:TYPE_TOUCH、TYPE_NON_TOUCH,是为了解决快速滑动后Fling的传递问题,使得滑动Fling可以在父View、子View之间传递。TYPE_TOUCH指用户手指在屏幕上滑动,TYPE_NON_TOUCH为用户手指离开屏幕后的滑动,即Fling。
综上,如果你不涉及Fling,则使用View、ViewGroup里面的函数也可实现滑动交互,但还是推荐实现接口的方法,更加清楚简洁。
现在新的RecyclerView、NestedScrollView都是使用的接口的形式实现,而比较老的ListView、ScrollView则是使用的ViewGroup中的方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容