Home > Enterprise >  Cannot set a character count limit on Textfield Android Jetpack Compose
Cannot set a character count limit on Textfield Android Jetpack Compose

Time:11-03

I'm developing an Android app using Jetpack Compose. I'd like to set a character count limit on Textfield, but if I try this code, users can input maximum 1201 characters(maxChar 1), and if users input 1201 characters(exceed maxChar), they cannot delete any letters.

@Composable
fun PostEdit(navController: NavController, content: String, id: String) {
    var editedContent = remember { mutableStateOf("$content")}
    val maxChar = 1200
    ...

         OutlinedTextField(
                value = editedContent.value,         
                onValueChange = { newValue: String ->
                    if (editedContent.value.length <= maxChar) {
                        editedContent.value = newValue
                    }
                },
                label = { Text("Content", fontSize = 20.sp, color = Brown) },
                ...

On a different view, I set a character count limit, too, and it is successful. The difference is, this time, there is no parameter in "var intro". This is the code.

@Composable
fun Signup(navController: NavController) 
    var intro by remember { mutableStateOf("") }
    val maxChar = 100
    ...
         OutlinedTextField(
                value = intro,
                onValueChange = {
                    if (it.length <= maxChar) {
                        intro = it
                    }
                },
                label = { Text("Introduction", fontSize = 20.sp, color = Brown) },
                ...

Could someone help me? Thank you.

CodePudding user response:

The second one (intro) you are using the implicit it parameter not the intro state variable

 onValueChange = { // <-- implicit `it`
         if (it.length <= maxChar) {
              intro = it 
          }
 }

while on the second (editedContent) one you are using the state variable instead so when editedContent's length reaches 1200 and you typed another character it will still satisfy your onValueChange condition <=, making it 1201, and when you attempt to delete, the condition won't be satisfied anymore, no changes will happen to editedContent

onValueChange = { newValue: String -> // <--  use this
     if (editedContent.value.length <= maxChar) {
          editedContent.value = newValue 
     }
}

so do what you did on the second one to your first one and it will work

 onValueChange = { newValue: String ->
     if (newValue.length <= maxChar) {
          editedContent.value = newValue
     }
 }
  • Related