Skip to content

列表与网格 (Lists)

源:Compose 列表和网格

对于大量数据,Compose 提供了延迟加载(Lazy)组件,仅在进入视口时才渲染元素。

1. 常用组件对比

组件用途对应 View 系统的实现
LazyColumn垂直滚动的列表RecyclerView + LinearLayoutManager
LazyRow水平滚动的列表RecyclerView (Horizontal)
LazyVerticalGrid垂直滚动的网格RecyclerView + GridLayoutManager
LazyHorizontalGrid水平滚动的网格RecyclerView (Horizontal Grid)

2. 基础用法

kotlin
val itemsList = (0..100).toList()

LazyColumn(
    contentPadding = PaddingValues(16.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp)
) {
    item { Text("列表头部") }
    
    items(itemsList) { index ->
        Text("第 $index 项数据")
    }
}
kotlin
LazyVerticalGrid(
    columns = GridCells.Fixed(3), // 固定 3 列
    // columns = GridCells.Adaptive(minSize = 128.dp) // 自适应
) {
    items(data) { item ->
        ImageItem(item)
    }
}

3. 性能优化:使用 Key

为什么需要 Key?

默认使用索引作为 key。如果列表发生重新排序,Compose 会销毁并重建所有项目。提供唯一的 key 允许 Compose 只移动对应的组件,极大提升性能。

kotlin
LazyColumn {
    items(
        items = messages,
        key = { it.id } // 使用唯一 ID 作为 Key
    ) { message ->
        MessageItem(message)
    }
}

4. 监听滚动状态

kotlin
val listState = rememberLazyListState()

// 只有滚动超过 0 时才显示按钮
val showButton by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 0 }
}

LazyColumn(state = listState) { /* ... */ }