解决安卓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);
相关推荐
q***046316 小时前
Spring Cloud Alibaba 组件版本选择
android·前端·后端
w***488216 小时前
解决报错net.sf.jsqlparser.statement.select.SelectBody
android·前端·后端
k***38816 小时前
MySQL 字符串日期格式转换
android·数据库·mysql
v***913016 小时前
数据库高安全—openGauss安全整体架构&安全认证
android·前端·后端
Kapaseker16 小时前
Android分层没搞懂,外包转岗难成功
android·kotlin
2501_9160088916 小时前
uni-app 上架到 App Store 的项目流程,构建、打包与使用开心上架(Appuploader)上传
android·ios·小程序·https·uni-app·iphone·webview
yuuki23323316 小时前
【C++】类和对象(中)
android·java·c++·后端
00后程序员张16 小时前
怎么在 iOS 上架 App,从构建端到审核端的全流程协作解析
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_9159184116 小时前
iOS 开发者工具全景指南,构建高效开发、调试与性能优化的多工具工作体系
android·ios·性能优化·小程序·uni-app·iphone·webview
qq_4179165316 小时前
HTML中的列表
android·前端·html