Android Compose:如何让Row中Text自适应宽度且不挤出右侧Image?
解决方案:让Text自适应宽度且长文本时自动截断并保留Image
要实现短文本自适应宽度、长文本自动截断,同时保证右侧Image始终显示,只需要修改Text的weight modifier,添加fill = false参数即可:
修改后的代码
@Composable fun TitleAndChevron() { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(8.dp) .background(color = Color.Black) .wrapContentWidth(align = Alignment.Start), ) { Text( text = "The Englishman Who Went Up a Hill But Came Down a Mountain", color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleLarge, modifier = Modifier .padding(8.dp) .weight(1f, fill = false) // 关键修改:添加fill = false ) Image( painter = painterResource(id = R.drawable.ic_chevron), contentDescription = null, modifier = Modifier .padding(start = 8.dp, end = 8.dp) .size(12.dp), ) } }
原理说明
- 默认的
weight(1f)会启用fill = true,强制Text占据Row中所有剩余可用宽度,所以短文本时也会撑满空间 - 设置
fill = false后,Text会优先以自身内容的实际宽度布局;当文本过长时,才会扩展到Row的剩余空间,并触发maxLines = 1和overflow = TextOverflow.Ellipsis的截断逻辑,同时右侧Image的布局空间会被优先保留,不会被挤出
内容的提问来源于stack exchange,提问作者Karla Droege
相关产品推荐
相关产品推荐

