Is there any out of the box solution for limiting the character size in TextField's ? I don't see any maxLength parameter like we had in XML.
You can use the onValueChange
parameter to limit the number of characters.
var text by remember { mutableStateOf("") }
val maxChar = 5
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
}
singleLine = true,
)
Then with M3 you can use the supportingText
attribute to display the counter text
.
Something like:
val maxChar = 5
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
modifier = Modifier.fillMaxWidth(),
supportingText = {
Text(
text = "${text.length} / $maxChar",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.End,
)
},
)
With M2 there isn't a built-in parameter.
In this case to display the counter text you can use something like:
val maxChar = 5
Column(){
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "${text.length} / $maxChar",
textAlign = TextAlign.End,
style = MaterialTheme.typography.caption,
modifier = Modifier.fillMaxWidth().padding(end = 16.dp)
)
}
text = it.take(maxChar)
better? –
Ordain You can use take function - here documentation
onValueChange = { onYearChanged(it.take(limitNum)) })
For example, if you will use it in function.
const val limitNum = 4
@Composable
fun YearRow(
modifier: Modifier = Modifier,
year: Int,
onYearChanged: (String) -> Unit,
) {
OutlinedTextField(
modifier = modifier,
value = if (year == 0) "" else "$year",
onValueChange = { onYearChanged(it.take(limitNum)) },
)
}
Trim the most recently inserted character according to selection
, if the new string exceeds the length.
fun TextFieldValue.ofMaxLength(maxLength: Int): TextFieldValue {
val overLength = text.length - maxLength
return if (overLength > 0) {
val headIndex = selection.end - overLength
val trailIndex = selection.end
// Under normal conditions, headIndex >= 0
if (headIndex >= 0) {
copy(
text = text.substring(0, headIndex) + text.substring(trailIndex, text.length),
selection = TextRange(headIndex)
)
} else {
// exceptional
copy(text.take(maxLength), selection = TextRange(maxLength))
}
} else {
this
}
}
Usage:
val (phone, setPhone) = remember {
mutableStateOf(TextFieldValue())
}
PaddingTextField(
value = phone,
onValueChange = { newPhone ->
setPhone(newPhone.ofMaxLength(11))
}
)
The first answer to this question works fine, but it´s true that in some cases there is an error that when exceeding the number of characters allowed, the value of the texfield is cleared. This failure seems to be due to predictive text, because if predictive text is disabled in android, it does not happen. One solution I found for now as a workaround is to use focusManager to "limit writing".
First, we need to get the focus manager to control the focus on the screen. We can do this, by adding this line inside our composable function:
val focusManager = LocalFocusManager.current
Then, in our TextField we can use the focusManager to avoid the user to write more than the maxChar limit. We can move the focus to the next element, clear the focus when the maxChar limit is exceeded or receive a lambda function and perform the action we want . That depends on us.
var text by remember { mutableStateOf(TextFieldValue("")) }
val maxChar = 10
TextField(
singleLine = true,
value = text,
onValueChange = {
// This line will take (in case the user try to paste a text from the clipboard) only the allowed amount of characters
text = it.take(maxChar)
if (it.length > maxChar){
focusManager.moveFocus(FocusDirection.Down) // Or receive a lambda function
}
}
)
In this way the user could never write more characters than what is established by the limit. Obviously, this is an alternative solution, which in my case solved my problem, now we have to wait to see if they add it natively
Logic that will allow your user to hit the max length and then delete after
Code:
@Composable
fun CustomTextField(
streamTitle:String,
updateText:(String)->Unit
){
val maxlength = 141
TextField(
value = streamTitle,
onValueChange = {
if (streamTitle.length <= maxlength || it.length < streamTitle.length) {
updateText(it)
}
}
Explanation
streamTitle.length <= maxlength
is the typical logic that will stop the user from entering text once the maxlength is hit. This has a problem that it willNOT
allow the user to delete any text due to the maxLength being hit.The additional logic of
it.length < streamTitle.length
is needed to combat the previously mentioned scenario. When a user deletes a character onValueChange() is called with new value ofit
minus the character deleted. Meaning that if our user has reached maxlength they will trigger our second conditional and now be allowed to delete characters
Another way to do this that could be considered more flexible is something like:
Text(
text = "A string with a lot of charsssssssssssssssssssssssssss"
modifier = Modifier.fillMaxWidth(.5f),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
this will constraint the width with the fillMaxWidth
bit and the height with the maxLines
part. If both of those constraints are hit the text will overflow and the behavior for overflow can be specified
in this case once the text occupied half of the view or went more than one line it would end up something like A string with a lot of charsssss...
© 2022 - 2024 — McMap. All rights reserved.
maxChar
chars it works fine. Then for next char it won't show any new char (correct behaviour) but when typing another char (7th formaxChar = 5
) it clearsTextField
and allows for new char inputs. Any explanation why it behaves like this and maybe possible fix? – Isocline