如何让Jetpack Compose的stickyHeader匹配LazyRow高度?
解决LazyRow粘性头部匹配高度的问题
要实现粘性头部铺满LazyRow高度且文字垂直居中,你可以通过以下两种方式修改代码:
方案一:适配动态高度(推荐)
给LazyRow添加固有尺寸测量修饰符,让它根据最高子项确定自身高度,再给粘性头部设置铺满高度和垂直居中:
@OptIn(ExperimentalFoundationApi::class) @Preview(showBackground = true) @Composable fun TestPreview() { LazyRow( modifier = Modifier.height(IntrinsicSize.Max) ) { stickyHeader { Text( "Header", modifier = Modifier .background(Color.Cyan) .fillMaxHeight() .wrapContentHeight(Alignment.CenterVertically) ) } items(10) { Text( "Hello World", modifier = Modifier .size(200.dp) .background(Color.Blue) ) } } }
方案二:固定头部高度(适用于子项高度固定场景)
如果列表项高度是固定值(比如示例中的200dp),直接给粘性头部设置相同高度并居中文字:
@OptIn(ExperimentalFoundationApi::class) @Preview(showBackground = true) @Composable fun TestPreview() { LazyRow { stickyHeader { Text( "Header", modifier = Modifier .background(Color.Cyan) .height(200.dp) .wrapContentHeight(Alignment.CenterVertically) ) } items(10) { Text( "Hello World", modifier = Modifier .size(200.dp) .background(Color.Blue) ) } } }
原理说明
- 方案一中的
IntrinsicSize.Max会让LazyRow自动测量所有子项的高度,取最大值作为自身高度,此时粘性头部的fillMaxHeight()就能正确铺满整个LazyRow的高度。 wrapContentHeight(Alignment.CenterVertically)用于让文字在头部区域内垂直居中显示。
内容的提问来源于stack exchange,提问作者Ziem
相关产品推荐
相关产品推荐

