解决安卓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);
相关推荐
NPE~19 分钟前
[App逆向]脱壳实战
android·教程·逆向·android逆向·逆向分析
木易 士心38 分钟前
别再只会用 drawCircle 了!一文搞懂 Android Canvas 底层机制
android
AtOR CUES2 小时前
MySQL——表操作及查询
android·mysql·adb
怣疯knight3 小时前
安卓App无法增加自定义图片作为图标功能
android
jinanwuhuaguo5 小时前
OpenClaw联邦之心——从孤岛记忆到硅基集体潜意识的拓扑学革命(第二十三篇)
android·人工智能·kotlin·拓扑学·openclaw
Gary Studio6 小时前
安卓HAL C++基础-命名域
android
诸神黄昏EX7 小时前
Android Google XTS
android
eSsO KERF7 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
pengyu9 小时前
【Kotlin 协程修仙录 · 筑基境 · 后阶】 | 调度器的艺术:Dispatchers 四大护法与 withContext 性能密码
android·kotlin
uElY ITER9 小时前
MySQL 中如何进行 SQL 调优
android·sql·mysql