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

Jetpack Compose:includeFontPadding弃用,求替代方案及官方修复说明

关于Jetpack Compose中PlatformTextStyle.includeFontPadding弃用的替代方案与官方说明

一、替代方案

PlatformTextStyle.includeFontPadding已被弃用,官方推荐使用TextStyle中的lineHeightStyle参数替代,通过LineHeightStyle可更精细地控制文本垂直对齐与内边距裁剪。

原代码中includeFontPadding = false的效果,对应设置LineHeightStyle.Trim.Both(裁剪文本上下额外内边距),搭配LineHeightStyle.Alignment.Center确保文本在lineHeight范围内居中。修改后的TextStyle代码如下:

val headlineRegular: TextStyle = TextStyle(
    fontWeight = FontWeight.W400,
    fontSize = 16.sp,
    lineHeight = 22.4.sp,
    letterSpacing = 0.3.sp,
    lineHeightStyle = LineHeightStyle(
        alignment = LineHeightStyle.Alignment.Center,
        trim = LineHeightStyle.Trim.Both
    )
)

二、官方对该属性的修复与优化

  1. 跨平台统一:原includeFontPadding是Android平台特有属性,不适用于Compose跨场景,弃用后改用lineHeightStyle实现跨平台一致的文本布局逻辑。
  2. 布局精度提升:原属性仅能简单开关字体内边距,lineHeightStyle支持更精细的对齐(顶部/居中/底部)和裁剪(仅顶部/仅底部/双向)设置,适配不同字体排版需求。
  3. 解决表现不一致问题:原属性在不同字体、设备上的内边距表现差异大,新的lineHeightStyle基于Compose统一文本测量逻辑,确保布局效果稳定可控。

三、解决TextButton中文本居中问题

结合你提供的TextButton代码,文本无法与图标垂直居中的核心原因是未正确配置文本内边距裁剪与对齐。修改后完整代码示例:

TextButton(
    modifier = modifier,
    enabled = enabled,
    colors = colors,
    onClick = onClick
) {
    Icon(
        painter = painterResource(id = R.drawable.ic_logout),
        contentDescription = "Logout icon",
        modifier = Modifier.align(Alignment.CenterVertically)
    )
    Spacer(modifier = Modifier.width(4.dp))
    Text(
        text = stringResource(R.string.logout),
        style = LocalAppType.current.headlineRegular
    )
}

同时确保headlineRegular已添加上述lineHeightStyle配置,即可让文本与图标在TextButton中垂直居中对齐。

(补充说明:设置includeFontPadding=true时,文本上下会保留字体自带的额外内边距,整体高度偏大;不设置该属性时,默认仍会保留部分内边距,因此都无法与图标对齐。通过lineHeightStyle裁剪内边距并居中对齐后,文本高度贴合实际内容,实现与图标的垂直居中。)

内容的提问来源于stack exchange,提问作者user924

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:57