如何在Android Jetpack Compose中调整OutlinedTextField高度并避免文本截断
解决OutlinedTextField固定高度后文本截断问题
要实现50dp高度、17sp字号文本垂直居中且不截断,核心是调整输入框的内部内容内边距——默认的上下内边距会挤占文本空间,导致截断。修改代码如下:
OutlinedTextField( value = emailText, onValueChange = { text -> emailText = text }, modifier = Modifier .fillMaxWidth() .height(50.dp) .padding(horizontal = 16.dp) .onFocusEvent { coroutineScope.launch { bringIntoViewRequester.bringIntoView() } }, shape = RoundedCornerShape(5.dp), label = { Text(text = "Email Address") }, // 关键:覆盖默认contentPadding,调整上下内边距让文本垂直居中 contentPadding = PaddingValues( vertical = 12.dp, horizontal = 16.dp // 若modifier已有horizontal padding,可设为0.dp避免重复 ), colors = TextFieldDefaults.textFieldColors( textColor = Color.White, focusedLabelColor = SignInTextColor, unfocusedLabelColor = SignInTextColor, focusedIndicatorColor = SignInTextColor, unfocusedIndicatorColor = SignInTextColor, containerColor = Color.Transparent ), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email, imeAction = ImeAction.Next ), // 可选:确保文本行高适配17sp字号,避免行高过大导致截断 textStyle = TextStyle(fontSize = 17.sp, lineHeight = 20.sp) )
原理说明
- 默认
OutlinedTextField的contentPadding上下值约为16.dp,在50dp高度下会压缩文本显示空间,导致截断。通过手动设置vertical内边距(比如12.dp),给17sp字号的文本留出足够垂直空间,同时保证整体高度为50dp。 - 若
modifier中已有horizontal = 16.dp的padding,可将contentPadding的horizontal设为0.dp,避免内边距叠加导致输入区域过窄。 - 显式设置
textStyle的lineHeight,确保文本行高与字号匹配,进一步避免截断。
这样调整后,输入文本会垂直居中,字号保持17.sp,标签也能正常浮动到边框上方,不会出现截断问题。
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

