[英]How to correctly set height in TextField in Jetpack Compose?
So I have this textfield,所以我有这个文本字段,
var value = remember { mutableStateOf("") }
OutlinedTextField(
value = value.value,
placeholder = {
Text("Search Users")
},
singleLine = true,
modifier = Modifier.height(40.dp),
onValueChange = {
value.value = it
},
)
I am setting height to 40.dp
as you can see.如您所见,我将高度设置为
40.dp
However it looks like this,然而它看起来像这样,
Looks like the text/placeholder is cut off.看起来文本/占位符被切断了。 How to fix this?
如何解决这个问题?
I run into same problem using OutlinedTextField.我使用 OutlinedTextField 遇到了同样的问题。 Obviously, this is material component that have exact padding, that is causing crop on text (even with smaller font size).
显然,这是具有精确填充的材质组件,这会导致文本裁剪(即使字体较小)。
Here is result:这是结果:
Solution is to use BasicTextField, and here is the code:解决方案是使用 BasicTextField,代码如下:
@Composable
private fun CustomTextField(
modifier: Modifier = Modifier,
leadingIcon: (@Composable () -> Unit)? = null,
trailingIcon: (@Composable () -> Unit)? = null,
placeholderText: String = "Placeholder",
fontSize: TextUnit = MaterialTheme.typography.body2.fontSize
) {
var text by rememberSaveable { mutableStateOf("") }
BasicTextField(modifier = modifier
.background(
MaterialTheme.colors.surface,
MaterialTheme.shapes.small,
)
.fillMaxWidth(),
value = text,
onValueChange = {
text = it
},
singleLine = true,
cursorBrush = SolidColor(MaterialTheme.colors.primary),
textStyle = LocalTextStyle.current.copy(
color = MaterialTheme.colors.onSurface,
fontSize = fontSize
),
decorationBox = { innerTextField ->
Row(
modifier,
verticalAlignment = Alignment.CenterVertically
) {
if (leadingIcon != null) leadingIcon()
Box(Modifier.weight(1f)) {
if (text.isEmpty()) Text(
placeholderText,
style = LocalTextStyle.current.copy(
color = MaterialTheme.colors.onSurface.copy(alpha = 0.3f),
fontSize = fontSize
)
)
innerTextField()
}
if (trailingIcon != null) trailingIcon()
}
}
)
}
calling it with changed background shape:用改变的背景形状调用它:
CustomTextField(
leadingIcon = {
Icon(
Icons.Filled.Search,
null,
tint = LocalContentColor.current.copy(alpha = 0.3f)
)
},
trailingIcon = null,
modifier = Modifier
.background(
MaterialTheme.colors.surface,
RoundedCornerShape(percent = 50)
)
.padding(4.dp)
.height(20.dp),
fontSize = 10.sp,
placeholderText = "Search"
)
您可以设置 minHeight 而不是使用高度:
modifier = Modifier.defaultMinSize(minHeight = 40.dp)
See the problem is that the font size is too big for the provided height.看到问题是字体大小对于提供的高度来说太大了。 The correct way to provide a height for the field is using the modifiers as you already are doing.
为字段提供高度的正确方法是使用修饰符,就像您已经在做的那样。 However, to work around this problem either increase the height of the text field or decrease the size of the font.
但是,要变通解决此问题,请增加文本字段的高度或减小字体的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.