JetPack Compose中Card内Row的weight()失效问题求助
Jetpack Compose中Row内weight组件无法显示的解决方案
核心问题定位
你的代码中Card的Modifier错误设置了固定宽度width(40.dp),这直接覆盖了fillMaxWidth()的效果,导致Card的可用空间被强制压缩到40dp,Row内的第二个Text组件即使设置了weight(1f)也没有足够的显示空间,所以无法被看到。此外还有几处Modifier顺序和冗余设置的问题需要调整。
修正后的完整代码
data class Test( val title: String, val text: String ) @Composable fun CardRowSample( modifier: Modifier = Modifier, ) { val testList = listOf( Test("AAAA", "1,2,3,4,5,6,7,8,9,10"), Test("BBBB", "11,12,13,14,15,16,17,18,19,20") ) LazyColumn( modifier = modifier ) { items(testList) { test -> Card( elevation = 12.dp, backgroundColor = Color.LightGray, modifier = Modifier .fillMaxWidth() .heightIn(min = 50.dp) // 移除错误的固定宽度设置 // 移除不必要的requiredHeight限制 .border( width = 1.dp, color = Color.Black, shape = RectangleShape ) // 将padding调整到border之后,避免border包含padding区域 .padding( horizontal = 20.dp, vertical = 20.dp ) ) { Row( modifier = Modifier.fillMaxWidth() ) { Icon( modifier = Modifier .padding(horizontal = 5.dp) .align(Alignment.CenterVertically), imageVector = Icons.Filled.Check, contentDescription = null ) Text( text = test.title, fontSize = 20.sp, modifier = Modifier .width(120.dp) .padding(horizontal = 10.dp, vertical = 10.dp) ) Text( text = test.text, fontSize = 20.sp, modifier = Modifier .weight(1f) .padding(horizontal = 10.dp, vertical = 10.dp) ) } } } } }
关键修改说明
- 移除Card的
width(40.dp):fillMaxWidth()已经让Card占满父容器宽度,固定宽度会直接压缩布局空间,导致内部组件无足够空间显示。 - 调整Modifier顺序:
padding放在border之后,这样border会紧贴Card内容,而不是包含padding区域,符合常规视觉逻辑。 - 移除冗余的
requiredHeight:heightIn(min = 50.dp)已经能保证Card的最小高度,无需额外设置固有高度限制。
修改后,Row的fillMaxWidth()会正常生效,第二个Text的weight(1f)会自动占据Icon和第一个Text之外的剩余空间,实现你期望的布局效果。
内容的提问来源于stack exchange,提问作者tofu
相关产品推荐
相关产品推荐

