解决安卓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);
相关推荐
没有了遇见5 小时前
Android 原生定位(替代高德 / 百度等三方定位)<终极版本>
android
2501_916008895 小时前
iOS 抓包工具有哪些?全面盘点主流工具与功能对比分析
android·ios·小程序·https·uni-app·iphone·webview
2501_915921435 小时前
iOS混淆工具实战 视频流媒体类 App 的版权与播放安全保护
android·ios·小程序·https·uni-app·iphone·webview
CYRUS_STUDIO6 小时前
LLVM 全面解析:NDK 为什么离不开它?如何亲手编译调试 clang
android·编译器·llvm
CYRUS_STUDIO6 小时前
静态分析神器 + 动态调试利器:IDA Pro × Frida 混合调试实战
android·逆向
g_i_a_o_giao9 小时前
Android8 binder源码学习分析笔记(一)
android·java·笔记·学习·binder·安卓源码分析
翻滚丷大头鱼9 小时前
android 四大组件—BroadcastReceiver
android
人生游戏牛马NPC1号9 小时前
学习 Android (二十) 学习 OpenCV (五)
android·opencv·学习
2501_916008899 小时前
uni-app iOS 日志与崩溃分析全流程 多工具协作的实战指南
android·ios·小程序·https·uni-app·iphone·webview
文 丰9 小时前
【AndroidStudio】官网下载免安装版,AndroidStudio压缩版的配置和使用
android