Jetpack Compose TextField文本对齐异常且被截断问题求助
问题
设置了一个方形TextField输入框,希望在其中显示单个24sp的字符。外层Box尺寸设为52.dp,空间充足,但字符却下移并被截断。代码及效果截图如下:
var inputChar by remember { mutableStateOf("2") } Box( modifier = Modifier .size(52.dp) .border( width = 1.dp, color = Color.Black, shape = RoundedCornerShape(5.dp) ) .aspectRatio(1f) ) { TextField( value = inputChar, onValueChange = { newText -> inputChar = newText }, keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number), modifier = Modifier.fillMaxSize(), textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.Center) .merge(TextStyle(fontSize = 24.sp)), colors = TextFieldDefaults.textFieldColors( backgroundColor = Color.LightGray, cursorColor = Color.Black, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent ), shape = RoundedCornerShape(5.dp), singleLine = true, ) }

解决方案
问题源于TextField默认的内边距和行高设置,通过以下调整即可解决:
- 移除TextField默认内边距:给TextField的modifier添加
padding(0.dp),避免内边距挤压文本空间 - 统一行高与字体大小:在textStyle中设置
lineHeight = 24.sp,消除文本垂直偏移 - 限制输入长度:在onValueChange中过滤文本,确保仅保留单个字符,匹配需求场景
修改后的完整代码:
var inputChar by remember { mutableStateOf("2") } Box( modifier = Modifier .size(52.dp) .border( width = 1.dp, color = Color.Black, shape = RoundedCornerShape(5.dp) ) .aspectRatio(1f) ) { TextField( value = inputChar, onValueChange = { newText -> inputChar = newText.take(1) }, keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number), modifier = Modifier .fillMaxSize() .padding(0.dp), textStyle = LocalTextStyle.current.copy( textAlign = TextAlign.Center, fontSize = 24.sp, lineHeight = 24.sp ), colors = TextFieldDefaults.textFieldColors( backgroundColor = Color.LightGray, cursorColor = Color.Black, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent ), shape = RoundedCornerShape(5.dp), singleLine = true, ) }
内容的提问来源于stack exchange,提问作者svguerin3
相关产品推荐
相关产品推荐

