Jetpack Compose maxlines on textField is not working

Viewed 1482

I'm making a todoapp and when im writing the todo i put to only have 1 line, but when i click Enter it creates a new lines, is there any way to fix it?

@Composable
fun TextFieldDemo() {
        Column(
            Modifier
                .padding(50.dp, 600.dp, 0.dp, 0.dp)
                .fillMaxHeight()) {
            val textState = remember { mutableStateOf(TextFieldValue()) }
            TextField(
                value = textState.value,
                onValueChange = { textState.value = it },
                label = {Text(text = "What you need Todo?")},
                singleLine = true //apenas uma linha de texto , podendo usar-se tambem singleLine = true

            )

        }
    }
3 Answers

Just set maxLines = 1 and singleLine = true,detect \n on onValueChange work for me

@Composable
fun SearchBar() {
            BasicTextField(
                textValue,
                onValueChange = {
                    if (!it.text.contains("\n"))
                        textValue = it
                },
                maxLines = 1,
                singleLine = true,
            )
}

On your on value changed callback you can check the text and filter out the new line character.

onValueChange = {
    textState.value = /* filter invalid chars from it */
},

Since Compose 1.0.0-alpha07, you can use maxLines to restrict the maximum lines of your text field:

TextField(
    onValueChange = {  },
    maxLines = 1
)
Related