You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose:实现iOS风格垂直选择器,动态设置LazyColumn高度显示5项

实现iOS风格垂直选择器的动态高度适配

要让LazyColumn始终刚好显示5个条目,无需固定高度,直接通过条目高度+间距动态计算总高度即可:

核心计算逻辑

每个条目高度为48.dp,5个条目之间存在4个间距(由Arrangement.spacedBy(8.dp)控制),因此总高度公式为:
总高度 = 单条目高度 × 5 + 间距 × 4

修改后的代码

val itemHeight = 48.dp
val spacing = 8.dp
val listHeight = itemHeight * 5 + spacing * 4

LazyColumn(
    modifier = Modifier
        .fillMaxWidth()
        .height(listHeight) // 替换固定高度为动态计算值
        .background(Color.Red),
    verticalArrangement = Arrangement.spacedBy(spacing),
    state = state,
    flingBehavior = rememberSnapFlingBehavior(lazyListState = state),
) {
    repeat(2) {
        item {
            Spacer(modifier = Modifier
                .fillMaxWidth()
                .height(itemHeight))
        }
    }
    items(option1) {
        Text(
            modifier = Modifier
                .fillMaxWidth()
                .height(itemHeight)
                .background(Color.Blue)
                .padding(vertical = 16.dp),
            text = it,
            textAlign = TextAlign.Center,
        )
    }
    repeat(2) {
        item {
            Spacer(modifier = Modifier
                .fillMaxWidth()
                .height(itemHeight))
        }
    }
}

Spacer(modifier = Modifier
    .fillMaxWidth()
    .height(40.dp)
    .background(color = Color(30, 30, 30, 40), RoundedCornerShape(12.dp)))

说明

  • 将条目高度和间距抽成独立变量,后续调整样式时只需修改这两个值,总高度会自动适配
  • 前后添加的Spacer是为了让首尾条目能滚动到中间选中位置,不影响可见区域的高度计算

内容的提问来源于stack exchange,提问作者Marian Pavel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:13:28