Home > Mobile >  Android jetpack compose textfield length while copy paste emoji
Android jetpack compose textfield length while copy paste emoji

Time:01-09

I need to restrict my textfield to take not more than 20 characters. My textfield allows emojis as well. Suppose, user has entered 19 characters and try to copy paste an emoji which is 2 characters length then the textfield should not allow it. My requirement is, if user is copy pasting content which is more than 20 characters length with or without emojis, then textfield should not allow it. How to do it in android compose textfield

CodePudding user response:

You can limit the characters in TextField in your onValueChange. For example, for limiting it to 20 characters do something like this:

var text by remember {
    mutableStateOf("")
}

TextField(value = text,
          onValueChange = {
              if(it.length <= 20) {
                  text = it
              }
          })

Here, if the length of characters entered in the TextField is smaller than or equal to 20, only then will the text variable be what is written in the TextField otherwise every other value won't be shown in the TextField.

CodePudding user response:

you can set a limit by accepting only 20 characters and if more than 20 characters you use the take function in kotlin to retrieve the first 20 characters pasted by the user

 var texts by remember {
    mutableStateOf("")
}

TextField(
    text = texts,
    onValueChange = {
        if (it.length <= 20) {
            texts = it
        } else {
            texts = it.take(20)
        }
    }
)
  •  Tags:  
  • Related