Resizeable BasicTextField in Jetpack Compose

11.9k Views Asked by At

Is there a way to produce a resizeable BasicTextField in Jetpack Compose, so that its width would wrap text size when a user types in or deletes characters? They've solved a similar problem for flutter, but I didn't find out how to solve this for Compose. Flutter - how to make TextField width fit its text ("wrap content")

var text: String by rememberSaveable { mutableStateOf("") }
BasicTextField(
   value = text,
   onValueChange = {
       text = it
   },
   modifier = Modifier.wrapContentWidth()
)

unfortunately, wrapContentWidth() doesn't work here.

2

There are 2 best solutions below

4
On BEST ANSWER

Well, looks like width(IntrinsicSize.Min) solves this problem:

var text: String by rememberSaveable { mutableStateOf("") }
BasicTextField(
   value = text,
   onValueChange = {
       text = it
   },
   modifier = Modifier.width(IntrinsicSize.Min)
)
5
On

We can specify the width range ( min and max width that the textField can span )

for width:-

modifier = Modifier.widthIn(1.dp, Dp.Infinity) // specified the min width as 1.dp

for height:-

modifier = Modifier.heightIn(1.dp, Dp.Infinity) 

The composable code:-

Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
     OutlinedTextField(
        value = text,
        onValueChange = {
           text = it
        },
        modifier = Modifier.widthIn(1.dp, Dp.Infinity)
     )
}

The TextField would grow when we type more till Dp.Infinity. ( used OutlinedTextField for demo but we can use BasicTextField )

enter image description here