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

问题分析:

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

问了下deepseek,给了个方案:

java 复制代码
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);
        }
    });
}

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

解决方案:

java 复制代码
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);
}

核心代码:

java 复制代码
linearLayoutManager.setStackFromEnd(true);
相关推荐
时寒的笔记1 分钟前
js逆向7_案例惠nong网
android·开发语言·javascript
肯多洛夫斯基1 小时前
安卓工控屏静默连WiFi全攻略
android
极梦网络无忧1 小时前
Android无障碍服务实现抖音直播间界面监控(场控助手核心原理)
android
call me by ur name2 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
kerli3 小时前
Compose 组件:Box 核心参数及其 Bias 算法
android·前端
BLUcoding3 小时前
Android 常用控件及核心属性
android
遥不可及zzz3 小时前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos
私人珍藏库3 小时前
【Android】一键硬核锁手机
android·智能手机·app·工具·软件
TTTao23334 小时前
自用Android项目框架备份
android
沃尔威武4 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql