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

如何测量Jetpack Compose中TextField高度并让相邻Button与其尺寸匹配

你可以通过Compose的固有特性测量(Intrinsic Measurement)实现两个组件高度自动匹配,无需手动测量高度,具体实现如下:

核心修改逻辑

  • 给每个包裹TextField和Button的Row添加Modifier.height(IntrinsicSize.Min),让Row高度自动适配内部最高子组件的高度
  • 给TextField和Button都添加Modifier.fillMaxHeight(),让二者填满Row的高度
  • 可选:给Button设置和TextField一致的圆角,视觉上更统一

修改后代码示例

val focusManager = LocalFocusManager.current
var code by remember { mutableStateOf("") }
var money by remember { mutableStateOf("") }

Column() {
    // 给Row添加固有高度测量
    Row(modifier = Modifier.height(IntrinsicSize.Min)) {
        TextField(
            // 添加fillMaxHeight
            modifier = Modifier
                .wrapContentSize()
                .fillMaxHeight(),
            value = code,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = {
                focusManager.clearFocus()
            }),
            singleLine = true,
            label = { Text("Code") },
            onValueChange = { pscCode ->
                code = pscCode.filter { it.isDigit() }.take(16)
            }
        )
        Button(
            modifier = Modifier
                .fillMaxWidth()
                // 添加fillMaxHeight
                .fillMaxHeight(),
            // 可选:设置和TextField一致的圆角
            shape = MaterialTheme.shapes.small,
            onClick = {…}
        )
        {
            Text("Save data")
        }
    }
    // 第二个Row做同样修改
    Row(modifier = Modifier.height(IntrinsicSize.Min)) {
        TextField(
            modifier = Modifier
                .wrapContentSize()
                .fillMaxHeight(),
            value = money,
            singleLine = true,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = {
                focusManager.clearFocus()
            }),
            label = { Text("Money amount") },
            onValueChange = { moneyAmount ->
                money = moneyAmount
                    .trim()
                    .replace(",", ".")
                    .take(5)
            }
        )

        Button(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),
            shape = MaterialTheme.shapes.small,
            onClick = {…}
        ) {
            Text("Clean data")
        }
    }
}

补充说明

如果你的业务场景需要自定义高度,也可以直接给Row设置固定高度比如Modifier.height(56.dp),内部组件同样fillMaxHeight()即可,适配性比固有测量更可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:18:00