Jetpack Compose 列表

延迟列表

系统会对所有列表项进行组合和布局,无论它们是否可见,因此如果您需要显示大量列表项(或长度未知的列表),则使用 [Column] 等布局可能会导致性能问题。

Compose 提供了一组组件,这些组件只会对在组件视口中可见的列表项进行组合和布局。这些组件包括 [LazyColumn] 和 [LazyRow]

`item()`\] 用于添加单个列表项,\[`items(Int)`\] 用于添加多个列表项: ![image.png](https://file.jishuzhan.net/article/1778350224218001410/e72332824a9576042ab4ab31d57fd791.webp) ```ts LazyColumn(modifier = modifier.fillMaxWidth(), contentPadding = PaddingValues(top = 100.dp)) { // Add a single item item { Text(modifier = Modifier.fillMaxWidth().height(50.dp).background(color = Color.Black).padding(all = 15.dp), text = "First item", color = Color.White) } // Add 5 items items(5) { index -> Text(modifier = Modifier.fillMaxWidth().height(50.dp).background(color = Color.Blue).padding(all = 15.dp), text = "Item: $index", color = Color.White) } // Add another single item item { Text(modifier = Modifier.fillMaxWidth().height(50.dp).background(color = Color.Green).padding(all = 15.dp), text = "Last item") } } ``` 还有许多扩展函数可用于添加列表项的集合,例如 `List`。借助这些扩展函数,我们可以轻松迁移上述 \[`Column`\] 示例 ![image.png](https://file.jishuzhan.net/article/1778350224218001410/cecc86bf140c9779951fbbdbea50ed36.webp) ```ts @Composable private fun example2(modifier:Modifier = Modifier) { val messages = arrayListOf("Title1","Title2", "Title3", "Title4", "Title5", "Title6", "Title7", "Title8") /** * import androidx.compose.foundation.lazy.items */ LazyColumn(modifier = modifier, contentPadding = PaddingValues(top = 100.dp)) { items(messages) { message -> MessageRow(message) } } } @Composable private fun MessageRow(message:String) { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier .fillMaxWidth() .height(150.dp) .padding(start = 15.dp, end = 15.dp, top = 15.dp) ) { Text( text = message, modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) } } ``` [上一篇 Jetpack Compose 分页器 Pager](https://juejin.cn/post/7356044171242864666 "https://juejin.cn/post/7356044171242864666")

相关推荐
_一条咸鱼_1 小时前
Android Runtime增量编译与差分更新机制原理(45)
android·面试·android jetpack
_一条咸鱼_1 天前
Android Runtime二进制镜像(ART Image)生成原理(44)
android·面试·android jetpack
_一条咸鱼_1 天前
Android Runtime全局优化与跨函数分析原理(43)
android·面试·android jetpack
alexhilton2 天前
使用用例(Use Case)以让Android代码更简洁
android·kotlin·android jetpack
_一条咸鱼_4 天前
Android Runtime即时编译触发条件与阈值深度解析(38)
android·面试·android jetpack
webbin4 天前
Compose @Immutable注解
android·android jetpack
webbin4 天前
Compose 副作用
android·android jetpack
Wgllss5 天前
大型异步下载器:基于kotlin+Compose+协程+Flow+Channel实现多文件异步同时分片断点续传下载
android·架构·android jetpack
_一条咸鱼_5 天前
Android Runtime JIT编译器核心技术原理分析(36)
android·面试·android jetpack
_一条咸鱼_5 天前
Android Runtime异常处理与跳转指令实现源码(35)
android·面试·android jetpack