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

如何在Row中垂直居中OutlinedTextField与FilledIconButton?

解决Jetpack Compose中Row内FilledIconButton与OutlinedTextField垂直对齐偏移问题

问题核心在于FilledIconButton默认自带顶部内边距,且它的默认容器尺寸和OutlinedTextField的高度不匹配。即便Row设置了verticalAlignment = Alignment.CenterVertically,按钮容器本身的顶部padding会让整个按钮视觉上偏上。

解决方案1:移除FilledIconButton的默认内边距

FilledIconButton提供了contentPadding参数,直接覆盖默认值即可消除多余的顶部内边距:

@Composable
fun PlayerInputField(
    playerName: String,
    onNameChange: (String) -> Unit,
    onAddPlayer: () -> Unit,
    onDeletePlayer: () -> Unit,
    commited: Boolean = false,
) {
    Row(
        modifier = Modifier
            .padding(horizontal = 10.dp, vertical = 0.dp)
            .wrapContentSize(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        OutlinedTextField(
            value = playerName,
            onValueChange = onNameChange,
            modifier = Modifier.weight(1f),
            label = { Text("Player Name") },
            singleLine = true
        )
        if (!commited) {
            FilledIconButton(
                onClick = onAddPlayer,
                contentPadding = PaddingValues(4.dp) // 替换默认内边距,可根据视觉效果微调
            ) {
                Icon(Icons.Filled.Add, "Add player")
            }
        } else {
            FilledIconButton(
                onClick = onDeletePlayer,
                contentPadding = PaddingValues(4.dp)
            ) {
                Icon(Icons.Filled.Clear, "Remove player")
            }
        }
    }
}

解决方案2:让按钮高度匹配TextField

如果调整内边距后仍有偏差,可以强制按钮高度和OutlinedTextField一致:

FilledIconButton(
    onClick = onAddPlayer,
    modifier = Modifier.height(TextFieldDefaults.MinHeight)
) {
    Icon(Icons.Filled.Add, "Add player")
}

解决方案3:改用基础IconButton自定义样式

如果不需要FilledIconButton的默认填充样式,直接用IconButton配合背景修饰符,完全自定义尺寸和内边距:

IconButton(
    onClick = onAddPlayer,
    modifier = Modifier
        .size(TextFieldDefaults.MinHeight)
        .background(MaterialTheme.colorScheme.primary, shape = MaterialTheme.shapes.small)
) {
    Icon(
        Icons.Filled.Add,
        "Add player",
        tint = MaterialTheme.colorScheme.onPrimary
    )
}

优先尝试方案1,它最贴合FilledIconButton的原有样式,只需微调内边距即可解决偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:16:03