如何解决Jetpack Compose固定高度TextField文本显示错位问题
问题根因
Jetpack Compose 自带的 TextField 组件默认内置了上下内边距,用来承载输入指示器、标签、占位符等附属元素,默认最小高度远高于你设置的28dp。你直接通过Modifier.height()强行限制高度时,内置的内边距会挤压文本的绘制区域,最终导致文本显示错位。
解决方案
修改TextField的contentPadding参数,自定义组件的内边距,取消默认的多余上下留白,即可适配你需要的小尺寸高度,修正后的参考代码如下:
Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .background(color = LightGray20, shape = RoundedCornerShape(6.dp)) .padding(6.dp) ) { TextField( modifier = Modifier .width(80.dp) .height(28.dp), value = product.quantity.toString(), onValueChange = { it.toDoubleOrNull()?.let { value -> quantityChangeHandler(product, value) } }, textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.End, fontSize = 16.sp), maxLines = 1, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onDone = { localFocusManager.clearFocus() } ), shape = RoundedCornerShape(8.dp), colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent, ), // 新增自定义内边距,可根据实际字体大小微调垂直边距 contentPadding = PaddingValues(horizontal = 8.dp, vertical = 3.dp) ) Text( text = description, fontSize = 16.sp, maxLines = 1, modifier = Modifier.padding(start = 2.dp) ) }
如果需要更灵活的自定义样式,也可以使用无默认样式的BasicTextField组件实现,它没有内置内边距,不会出现文本被挤压的问题。
内容的提问来源于stack exchange,提问作者Morozov
相关产品推荐
相关产品推荐

