14

Is it possible to set singleLine or maxLines on TextField?

I've checked a source and it's missing. Any ideas / workarounds?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Chesteer89
  • 141
  • 1
  • 1
  • 3

3 Answers3

17

You can use the parameter maxLines or singleLine:

TextField(
    //..
    maxLines = 1)

or

TextField(
    //..
    singleLine = true)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 2
    Is there any difference between those two? To me it looks like `singleLine` is redundant. – Daniel Weidensdörfer Nov 10 '21 at 11:11
  • I assuming the difference in Compose is the same as that of xml. See https://stackoverflow.com/questions/30879471/android-singleline-vs-maxlines – kc_dev Jan 01 '22 at 01:18
  • The documentation states that when `singleLine` is set to `true`, `maxLines` will automatically be set to `1`. However, neither setting stops the input to accept line breaks (e.g. from an external or keyboard that does not honor the `imeAction`). – AplusKminus Jun 24 '23 at 12:57
6

Since Compose 1.0.0-alpha08, you can use singleLine parameter to make the text field a single horizontally scrollable line:

TextField(
    value = text,
    onValueChange = { },
    singleLine = true
)
Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
0

I can't see any property which can do it directly. One work around could be:

TextField(
    value = yourText,
    onValueChange = { s: TextFieldValue ->
        if (s.text.count { it == '\n' } < 3) { // 3 lines (or two enters)
            yourText = s
        }
    }
)
nglauber
  • 18,674
  • 6
  • 70
  • 75