解决安卓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);
相关推荐
fatiaozhang95271 天前
中兴B860AV5.2-U_原机安卓4.4.2系统专用_晶晨S905L3SB处理器_线刷固件包
android·电视盒子·刷机固件·机顶盒刷机·中兴b860av5.2-u
儿歌八万首1 天前
Android 自定义 View 实战:打造一个跟随滑动的丝滑指示器
android·kotlin
我有与与症1 天前
Kuikly 实战:手把手撸一个跨平台 AI 聊天助手 (ChatDemo)
android
恋猫de小郭1 天前
Flutter UI 设计库解耦重构进度,官方解答未来如何适配
android·前端·flutter
apihz1 天前
全球IP归属地查询免费API详细指南
android·服务器·网络·网络协议·tcp/ip
hgz07101 天前
Linux环境下MySQL 5.7安装与配置完全指南
android·adb
Just_Paranoid1 天前
【Android UI】Android 添加圆角背景和点击效果
android·ui·shape·button·textview·ripple
梁同学与Android1 天前
Android ---【经验篇】阿里云 CentOS 服务器环境搭建 + SpringBoot项目部署(二)
android·spring boot·后端
风往哪边走1 天前
自定义简易日历
android