You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中LazyColumn无库实现无限滚动(需底部监听器)

在Jetpack Compose中用LazyColumn实现无限滚动(无第三方库)

要实现这个功能,核心是利用LazyListState跟踪滚动位置,判断用户滚动到列表底部时触发加载逻辑,全程不需要第三方库,具体实现如下:

1. 定义核心状态变量

先准备几个关键状态来控制列表和加载流程:

  • listState:跟踪LazyColumn的滚动状态,用rememberLazyListState()创建
  • items:存储列表展示的数据源
  • isLoading:标记是否正在加载,防止重复触发请求

代码示例:

val listState = rememberLazyListState()
var items by remember { mutableStateOf(List(20) { "Item $it" }) }
var isLoading by remember { mutableStateOf(false) }

2. 监听滚动状态,触发底部加载逻辑

用LaunchedEffect监听listState的滚动变化,通过计算可见项位置判断是否到达底部。这里设置为距离底部还有1个item时触发加载(提前触发避免用户等待),同时结合isLoading状态防止重复请求。

代码实现:

LaunchedEffect(listState) {
    snapshotFlow {
        // 获取最后一个可见项的索引
        val lastVisibleIndex = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
        // 判断是否接近底部
        lastVisibleIndex >= items.size - 1
    }
    .distinctUntilChanged() // 避免重复触发相同状态
    .collect { shouldLoadMore ->
        if (shouldLoadMore && !isLoading) {
            isLoading = true
            // 模拟异步加载(实际替换为网络请求/本地数据加载)
            delay(1000)
            items = items + List(10) { "New Item ${items.size + it}" }
            isLoading = false
        }
    }
}

3. 构建LazyColumn并添加加载提示

在LazyColumn中展示现有数据,同时在底部添加加载状态提示(当isLoading为true时显示):

完整LazyColumn代码:

LazyColumn(state = listState) {
    items(items) { item ->
        Text(
            text = item,
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            fontSize = 18.sp
        )
    }

    // 底部加载提示项
    item {
        if (isLoading) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                CircularProgressIndicator()
                Spacer(modifier = Modifier.width(8.dp))
                Text(text = "加载中...")
            }
        }
    }
}

关键细节说明

  • snapshotFlow将LazyListState的状态转换为数据流,方便监听滚动变化
  • distinctUntilChanged()确保只有状态真正变化时才执行逻辑,减少不必要的计算
  • 提前触发加载的逻辑可以根据需求调整(比如距离底部2个item时触发)
  • 必须严格维护isLoading状态,避免同一时间发起多个重复加载请求

内容的提问来源于stack exchange,提问作者beigirad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:52:38