35

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.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Stefan
  • 2,829
  • 5
  • 20
  • 44

5 Answers5

71

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,
        )
    },
)

enter image description here

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)
    )
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 5
    When using your snippet, if you type `maxChar` chars it works fine. Then for next char it won't show any new char (correct behaviour) but when typing another char (7th for `maxChar = 5`) it clears `TextField` and allows for new char inputs. Any explanation why it behaves like this and maybe possible fix? – adek111 Aug 01 '21 at 12:50
  • 6
    Will pasting a long text work with implementation? Isn't `text = it.take(maxChar)` better? – John Doe Aug 06 '21 at 16:42
  • @adek111 I am facing the same issue. Did you found any solution to it? – Sahil Aug 28 '21 at 11:00
  • @Sahil, unfortunately not, still waiting for explanation from Gabriele – adek111 Aug 28 '21 at 16:27
  • @adek111 I am facing the same issue. Did you find any solution to it? – Arpit Shukla Oct 25 '21 at 06:23
  • @ArpitShukla it should be fixed in Compose 1.2.0-alpha04 – adek111 Mar 11 '22 at 15:46
8

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)) },
  )
}
afollestad
  • 2,929
  • 5
  • 30
  • 44
lm e
  • 81
  • 1
  • 2
6

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

Ernesto Abreu
  • 61
  • 1
  • 2
5

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))
    }
)
Mankin Chung
  • 51
  • 1
  • 3
-3

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...

ink
  • 159
  • 2
  • 10