前言
上次文章中实现了简易的ScrollerView滑动,但实际使用中许多场景都会涉及到嵌套滑动,在今天的博文中我们基于上次的ScrollLayout来进一步实现嵌套滑动。
嵌套滑动预备知识:https://juejin.cn/post/6844904184911773709
整体页面结构
<?xml version="1.0" encoding="utf-8"?>
<com.example.nestedscroll.ScrollParentLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="300dp"
android:text="I'm TOP!"
android:gravity="center"
android:textSize="24sp"
android:background="@color/teal_700"/>
<com.example.nestedscroll.ScrollChildLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="I'm 1"
android:gravity="center"
android:textSize="24sp"
android:background="@color/red1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="I'm 2"
android:gravity="center"
android:textSize="24sp"
android:background="@color/red2"/>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="I'm 3"
android:gravity="center"
android:textSize="24sp"
android:background="@color/red1"/>
... 后边还有n个TextView
</com.example.nestedscroll.ScrollChildLayout>
</com.example.nestedscroll.ScrollParentLayout>
嵌套结构中父ViewGroup为ScrollParentLayout,子ViewGroup为ScrollChildLayout。
class ScrollParentLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
) : NestedScrollLayout(context, attrs), NestedScrollingParent3
class ScrollChildLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
) : NestedScrollLayout(context, attrs), NestedScrollingChild3
- ScrollParentLayout和ScrollChildLayout均继承自NestedScrollLayout(NestedScrollLayout为ScrollLayout的copy,以不修改ScrollLayout实现)以提供滑动功能
- ScrollParentLayout实现了NestedScrollingParent3接口,作为嵌套滑动的父控件
- ScrollChildLayout实现了NestedScrollingChild3接口,作为嵌套滑动的子控件
页面滑不动
运行后发现页面滑不动,查看NestedScrollLayout的onInterceptTouchEvent()实现,为简单实现滑动效果,上节中简单将NestedScrollLayout设置为拦截所有触摸事件。
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return true
}
这直接导致了页面滑不动,因为ScrollParentLayout其子View的高度经过onMeasure后都是固定的了&#