'Jetpack Compose Decrease height of TextField
I am trying to design a search bar like Google search bar with decreased height. But the Input text is getting cropped also the placeholder text.
TextField(
value = searchText.value,
singleLine = true,
onValueChange = {
searchText.value = it
},
placeholder = { //placeholder text is also getting cropped
Text(
text = "Search",
fontSize = 20.sp,
)
},
textStyle = TextStyle(fontSize = 20.sp), // input text is getting cropped
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp)
.height(45.dp), // Here I have decreased the height
shape = RoundedCornerShape(22.dp),
)
My Input text and Placeholder text getting 50% cropped. How to solve it?
Solution 1:[1]
I run into same problem using TextField. Obviously, this is material component that have exact padding, that is causing crop on text (even with smaller font size).
Here is result:
As comment suggested solution is to use BasicTextField, and here is the code:
@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"
)
Solution 2:[2]
A simpler way would be to scale it:
TextField(
value = "",
onValueChange = {},
modifier = Modifier.scale(scaleY = 0.9F, scaleX = 1F),
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zoran |
Solution 2 | Henry Ecker |