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

JetPack Compose计算器应用文本重叠问题求助

解决JetPack Compose计算器文本重叠问题

你的计算器文本重叠问题主要来自两个设置:

  • lineHeight = 40.sp远小于fontSize = 80.sp,导致文字纵向被挤压重叠
  • 文本过长时没有适配逻辑,超出宽度后出现截断或重叠

以下是具体修复方案:

1. 修复行高问题

把行高调整为与字号匹配或稍大的值,避免纵向挤压:

Text(
    text = state.number1 + (state.operation?.symbol ?: "") + state.number2,
    textAlign = TextAlign.End,
    modifier = Modifier
        .fillMaxWidth()
        .padding(vertical = 32.dp),
    fontWeight = FontWeight.Light,
    fontSize = 80.sp,
    color = Color.White,
    lineHeight = 80.sp, // 修改为与字号一致
    maxLines = 1
)

2. 添加文本自动缩小逻辑

当文本过长超出宽度时,自动缩小字体以适配,避免横向重叠或截断:

@Composable
fun Calculator(
    state: CalculatorState,
    modifier: Modifier = Modifier,
    buttonSpacing: Dp = 8.dp,
    onActions: (CalculatorActions) -> Unit
) {
    Box(modifier = modifier) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.BottomCenter),
            verticalArrangement = Arrangement.spacedBy(buttonSpacing)
        ) {
            val textScaleFactor = remember { mutableStateOf(1f) }
            Text(
                text = state.number1 + (state.operation?.symbol ?: "") + state.number2,
                textAlign = TextAlign.End,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 32.dp),
                fontWeight = FontWeight.Light,
                fontSize = 80.sp,
                color = Color.White,
                lineHeight = 80.sp,
                maxLines = 1,
                softWrap = false,
                textScaleFactor = textScaleFactor.value,
                onTextLayout = { layoutResult ->
                    if (layoutResult.didOverflowWidth) {
                        // 计算适配宽度的缩放比例
                        val availableWidth = layoutResult.size.width.toFloat()
                        val textWidth = layoutResult.totalWidth
                        textScaleFactor.value = availableWidth / textWidth
                    } else {
                        textScaleFactor.value = 1f
                    }
                }
            )
            // 原有按钮组件代码...
        }
    }
}

3. 可选:限制最大输入字符数

如果不想字体缩得太小,可以在业务逻辑中限制输入的最大字符数,从源头避免文本过长。

内容的提问来源于stack exchange,提问作者Subham Kumar Padhy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 04:09:56