Android 实现嵌套滑动

前言

Android实现简易版滑动

上次文章中实现了简易的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后都是固定的了&#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值