列表与网格 (Lists)
对于大量数据,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) { /* ... */ }