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")

相关推荐
png1 天前
从零开始Compose天气预报(完结)
android jetpack
阿巴斯甜2 天前
produceState的使用:
android jetpack
阿巴斯甜2 天前
snapshotFlow的使用
android jetpack
菜鸟国国2 天前
从0开始学Jetpack Compose|第二篇:基础组件+核心布局,从零搭建实用UI
android jetpack
simplepeng2 天前
mutableStateOf(list) vs mutableStateListOf():该如何选择?
android jetpack
zh_xuan2 天前
Android Jetpack DataStore存储数据
android·android jetpack·datastore
simplepeng3 天前
MVI with Jetpack Compose:让你的应用更简洁和整洁
android jetpack
simplepeng3 天前
别再让团队困惑:少有人提及的 MVI 命名规范
android jetpack
zh_xuan3 天前
Android Jetpack 使用Room数据库
android·android jetpack·room
alexhilton5 天前
Jetpack Compose中的富文本输入
android·kotlin·android jetpack