Compose中TextAlign.Center/Ellipsis导致文本每次重组右移?
Jetpack Compose中文本偏移问题分析
复现代码
Column { var isNextVisible by remember { mutableStateOf(false) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(20.dp) .background(Color.Blue) .clickable { isNextVisible = !isNextVisible }, ) if (isNextVisible) { Box( modifier = Modifier .size(30.dp) .background(Color.Red) ) } } Text( modifier = Modifier.fillMaxWidth(1f), text = "this is a long text that needs to be truncated. this is a long text that needs to be truncated. this is a long text that needs to be truncated. ", maxLines = 1, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis, ) }
问题现象
反复点击蓝色方块时,红色方块会显示或隐藏。每次重组时,Text组件内的文本会逐次向右偏移。测试发现使用textAlign = TextAlign.Start时无此问题,但使用TextAlign.Center或TextAlign.End且搭配TextOverflow.Ellipsis时,就会出现文本每次重组右移的现象,请问这是Compose的Bug吗?
问题分析与解决方案
这确实是Jetpack Compose在特定排版场景下的已知问题,属于文本截断与对齐组合时的计算精度偏差。当文本需要截断显示省略号,同时设置了居中或右对齐时,Compose在重组过程中对文本可用宽度的计算会产生累积误差,导致每次重组后文本位置逐步偏移。
临时解决方案:
- 用
Modifier.wrapContentWidth(align = Alignment.CenterHorizontally)替代textAlign = TextAlign.Center,结合fillMaxWidth使用,能规避排版计算的累积误差:Text( modifier = Modifier.fillMaxWidth().wrapContentWidth(align = Alignment.CenterHorizontally), text = "this is a long text that needs to be truncated...", maxLines = 1, overflow = TextOverflow.Ellipsis, ) - 将文本内容用
remember包裹,确保重组时文本的计算上下文稳定:val displayText by remember { mutableStateOf("this is a long text that needs to be truncated. this is a long text that needs to be truncated. this is a long text that needs to be truncated. ") }
内容的提问来源于stack exchange,提问作者Diken Mhrz
相关产品推荐
相关产品推荐

