当前位置: 首页 > news >正文

解决安卓recyclerView滚到底部不彻底问题

问题分析:

传统recycleview滚到到底部方式scrollToPosition(lastpositon),只能定位到最后一条数据的顶部。由于数据过长,无法滚动到最底部。

问了下deepseek,给了个方案:

private void recyclerViewScrollToBottom() {
    final int itemCount = chatListAdapter.getItemCount();
    if (itemCount == 0) return; // 处理空数据情况

    final LinearLayoutManager layoutManager = (LinearLayoutManager) viewBinding.recyclerView.getLayoutManager();
    if (layoutManager == null) return;

    final int lastPosition = itemCount - 1;
    
    // 使用标志位确保一次性滚动到底部
    layoutManager.scrollToPositionWithOffset(lastPosition, 0);
    viewBinding.recyclerView.post(() -> {
        // 添加高度有效性检查
        final int recyclerHeight = viewBinding.recyclerView.getHeight();
        if (recyclerHeight == 0) return;

        final View lastItem = layoutManager.findViewByPosition(lastPosition);
        if (lastItem == null) {
            // 如果视图未加载,改用保证性滚动方案
            viewBinding.recyclerView.smoothScrollToPosition(lastPosition);
            return;
        }

        final int bottomOffset = lastItem.getBottom() - recyclerHeight;
        if (bottomOffset > 0) {
            // 取消可能存在的未完成滚动
            viewBinding.recyclerView.stopScroll();
            viewBinding.recyclerView.smoothScrollBy(0, bottomOffset);
        }
    });
}

此方法滚动后会出现抖动问题,因为先定位到最后一条顶部,在滚动到底部,会有一个滚动效果。如果数据刷新太频繁、就会出现抖动现象。

解决方案:

private void recyclerViewScrollToBottom() {
        int itemCount = chatListAdapter.getItemCount();
        if (itemCount == 0)
            return;
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);
//        linearLayoutManager.scrollToPositionWithOffset(chatListAdapter.getItemCount() - 1, Integer.MIN_VALUE);
        viewBinding.recyclerView.setLayoutManager(linearLayoutManager);
}

核心代码:

linearLayoutManager.setStackFromEnd(true);

相关文章:

  • LeetCode每日精进:622.设计循环队列
  • Linux 病毒扫描工具 ClamAV 使用
  • 4*A100 部署 deepseek-r1-671B
  • Vue 报错error:0308010C:digital envelope routines::unsupported 解决方案
  • Web自动化之Selenium下Chrome与Edge的Webdriver常用Options参数
  • 【中等】59.螺旋矩阵Ⅱ
  • DeepSeek个人知识库
  • vscode设置自动换行
  • pnpm的基本用法
  • 【设计师专属】智能屏幕取色器Pro|RGB/HEX双模式|快捷键秒存|支持导出文档|C++ QT
  • vue3的实用工具库@vueuse/core
  • 【Unity】URP管线Shader编程实例详解 (1) : 漩涡效果shader
  • 10道Redis常见面试题速通
  • 网卡与网口全解析:从基础到Linux高级管理
  • 基于GO语言的车牌识别api技术-港澳车牌文字识别
  • 【JavaScript Day23】jQuery事件绑定及动画
  • 深度学习进阶:构建多层神经网络
  • 从零开始:在 MacOS 中通过 Docker 部署跨平台 Redis 服务(支持 Ubuntu 迁移)
  • 基于Redis 的分布式 session 图解
  • 计算重建dMRI与GrondTruth之间的角度误差图(AAE)代码实现(pytorch)
  • 权威访谈丨国家疾控局就《世界卫生组织大流行协定》答记者问
  • 交通运输局男子与两名女子办婚礼?官方通报:未登记结婚,开除该男子
  • 王毅同丹麦外交大臣拉斯穆森会谈
  • 慢品巴陵,看总编辑眼中的岳阳如何书写“山水人文答卷”
  • 上海小学生暑(寒)托班会增设开办期数、延长办班时间吗?团市委回应
  • 第十届青春文学奖揭晓,梁晓声获特别奖