Jetpack Compose 列表

延迟列表

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

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

`item()` 用于添加单个列表项,`items(Int)` 用于添加多个列表项:

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` 示例

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

相关推荐
hai_android2 天前
LiveEventBusCore 跨 Activity 通讯源码解析
android·kotlin·android jetpack
我命由我123455 天前
Android 广播 - 组件通信
android·java·开发语言·android studio·android jetpack·android-studio·android runtime
alexhilton6 天前
为什么你的 LazyColumn 仍然卡顿
android·kotlin·android jetpack
hai_android6 天前
Android 嵌套滑动冲突:内部拦截 vs 外部拦截实战
android·android studio·android jetpack
alexhilton10 天前
模块化Jetpack Compose架构
android·kotlin·android jetpack
hai_android10 天前
InputStage 责任链核心执行流程
android·android studio·android jetpack
传奇开心果编程11 天前
【现代声明式UI学与练】第4课 列表渲染与 key——如何高效渲染列表、key 的作用、列表重排时的状态保持
学习·flutter·react native·ui·swiftui·android jetpack
传奇开心果编程12 天前
【现代声明式UI学与练】第7课 组件通信——父传子、子传父、跨层级通信、状态提升与 Context
学习·flutter·react native·ui·swiftui·android jetpack
传奇开心果编程12 天前
【现代声明式UI学与练】第9课 性能优化——渲染优化、列表优化、内存优化、启动优化
学习·flutter·react native·ui·性能优化·swiftui·android jetpack
天空之城--14 天前
Android一周动态:Android 18首次官宣、Compose Material3 1.4转正(5趋势+5资讯)
android·人工智能·flutter·架构·android jetpack