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

如何通过代码控制NestedScrollView带延迟地缓慢平滑滚动?

解决NestedScrollView滚动过快的问题

你的代码里fullScroll(View.FOCUS_DOWN)是直接瞬间跳转到底部,无平滑过渡;默认的smoothScrollTo动画时长由系统控制,无法满足缓慢滚动的需求。可以通过自定义滚动动画时长实现缓慢平滑的滚动效果,具体方案如下:

实现思路

用ValueAnimator精确控制滚动过程和时长,替代原生的fullScroll和默认smoothScrollTo,自由设定滚动速度。

代码实现

1. 自定义平滑滚动到底部的方法

private void smoothScrollToBottom(NestedScrollView scrollView) {
    // 自定义滚动时长,这里设为2000毫秒(2秒),可按需调整
    int scrollDuration = 2000;
    // 计算滚动目标位置:子View总高度减去ScrollView自身高度
    int targetScrollY = scrollView.getChildAt(0).getHeight() - scrollView.getHeight();
    int currentScrollY = scrollView.getScrollY();
    
    ValueAnimator animator = ValueAnimator.ofInt(currentScrollY, targetScrollY);
    animator.setDuration(scrollDuration);
    animator.addUpdateListener(animation -> {
        // 实时更新滚动位置
        int currentValue = (int) animation.getAnimatedValue();
        scrollView.scrollTo(0, currentValue);
    });
    animator.start();
}

2. 自定义平滑滚动到顶部的方法

private void smoothScrollToTop(NestedScrollView scrollView) {
    // 同样设置2000毫秒的滚动时长
    int scrollDuration = 2000;
    int currentScrollY = scrollView.getScrollY();
    
    ValueAnimator animator = ValueAnimator.ofInt(currentScrollY, 0);
    animator.setDuration(scrollDuration);
    animator.addUpdateListener(animation -> {
        int currentValue = (int) animation.getAnimatedValue();
        scrollView.scrollTo(0, currentValue);
    });
    animator.start();
}

3. 调用方法实现滚动逻辑

// 先平滑滚动到底部
scroll_1.post(() -> smoothScrollToBottom(scroll_1));
// 等待底部滚动完成后,再平滑滚动到顶部(延迟时间与底部滚动时长一致)
scroll_1.postDelayed(() -> smoothScrollToTop(scroll_1), 2000);

注意事项

  • 可根据需求调整scrollDuration的数值,数值越大滚动越缓慢。
  • 延迟时间需和底部滚动时长保持一致,确保底部滚动完成后再启动向上滚动,避免动画冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:22:11