BasicTextField maxlength Bug. If you go over the maximum length, BasicTextField doesn't work normally

Viewed 526

My Code

I tried to limit the length to a maximum of 30 characters, but if I write more than 30 characters, it will no longer be entered or erased. Why is that?

What I want to do is create a view that acts like EditText in xml.

The function you want.

  • hint
  • maxLength

However, the above two functions are not supported in Jetpack Compose TextField().

@Composable
fun MyCustomEditText(
    placeholder: String = stringResource(id = "sample"),
) {
    var inputText by remember { mutableStateOf("") }

    BasicTextField(
        value = inputText,
        onValueChange = {if (it.length <= 30) inputText = it },
        singleLine = false,
        maxLines = 2,
        decorationBox = { innerTextField ->
            if (inputText.isEmpty()) { Text(text = placeholder)}
            innerTextField()
        }
    )
}

1 Answers
  1. You can use TextField or an OutlinedTextField to set a placeholder.

Eg :-

 TextField(
            value = someText,
            onValueChange = { someText = it },
            label = { Text("Simple TextField") }, // It will be shown on the top when focussed
            placeholder = { Text("Placeholder text") }, // It will be shown as hint when nothing is typed
          )
  1. you mentioned that you have limited the length by 30 characters and then tried to write more then 30 charac. also in the code I can see a condition where the length is fixed for 30 characters onValueChange = {if (it.length <= 30) inputText = it } So I am not sure how you can enter more then 30 char. in this textfield.
Related