You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestedScrollView停止滚动时Toolbar跳转异常问题求助

解决Toolbar惯性滚动中断后自动展开的异常问题

嘿,这个交互坑我之前做项目时也踩过!本质是CoordinatorLayout与NestedScrollView的滚动状态不同步导致的:当你给NestedScrollView一个fling惯性滚动,突然触摸停止时,NestedScrollView的滚动被中断,但AppBarLayout还在继续处理之前的fling动画,两者状态错位就触发了Toolbar莫名展开的回弹问题。

下面给你两个针对模板布局的轻量修改方案,能快速让交互变自然:

方法一:自定义NestedScrollView,同步滚动中断信号

这个方法最直接,通过重写NestedScrollView的嵌套滚动回调,确保触摸停止时通知AppBarLayout停止所有滚动动画:

class SyncScrollNestedScrollView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : NestedScrollView(context, attrs, defStyleAttr) {

    override fun onStopNestedScroll(target: View, type: Int) {
        super.onStopNestedScroll(target, type)
        // 找到父布局里的AppBarLayout,强制停止它的滚动动画
        val parent = parent as? CoordinatorLayout
        parent?.findViewById<AppBarLayout>(R.id.app_bar)?.let { appBar ->
            appBar.stopNestedScroll(type)
        }
    }
}

然后把布局里的<NestedScrollView>替换成你自定义的这个类:

<com.yourpackage.SyncScrollNestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <!-- 你的内容布局 -->
</com.yourpackage.SyncScrollNestedScrollView>

方法二:给AppBarLayout设置自定义Behavior

如果不想修改NestedScrollView,也可以给AppBarLayout加个自定义Behavior,拦截滚动状态:

class FixFlingBehavior : AppBarLayout.Behavior() {
    override fun onStopNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: AppBarLayout,
        target: View,
        type: Int
    ) {
        super.onStopNestedScroll(coordinatorLayout, child, target, type)
        // 当触摸停止时,立即结束AppBar的滚动动画
        if (type == ViewCompat.TYPE_TOUCH) {
            child.stopNestedScroll(type)
        }
    }
}

然后在布局的AppBarLayout里引用这个Behavior:

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="com.yourpackage.FixFlingBehavior">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        <!-- 你的Toolbar配置 -->
        >
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

这两个方案都能让触摸停止时,Toolbar和NestedScrollView的滚动状态完全同步,不会再出现莫名其妙的回弹展开,交互逻辑会顺畅很多~

内容的提问来源于stack exchange,提问作者pt2121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:11:02