Home > Enterprise >  OutlinedTextField doesn't resize to a minimumWidth in Compose
OutlinedTextField doesn't resize to a minimumWidth in Compose

Time:07-07

I'm trying to make an OutlinedTextField (see below image) act as "wrap-content". It would be ideal for it to be just big enough to fit the inside text 500g and expand and contract if user edits the field. If I remember correctly this was possible to do with the old views with the (non-Compose) ConstraintLayout but in Compose this isn't working.

So far I have tried adjusting various modifiers, (each separately):

.defaultMinSize(minWidth = 10.dp)

.width(IntrinsicSize.Min)

.widthIn(1.dp, Dp.Infinity)

.requiredWidth(IntrinsicSize.Min) 

I also tried putting the Row into a Compose ConstraintLayout, but nothing seems to work

If I set the size modifier to a small width it does reduce the width but it no longer expands...

Anyone was able to achieve this?

Outlined text field that needs to be small

CodePudding user response:

The OutlinedTextField has default min size.

You can achieve it using a OutlinedTextFieldDecorationBox together with BasicTextField, applying the modifier width(IntrinsicSize.Min).

Something like:

var text by remember { mutableStateOf("500") }
val interactionSource = remember { MutableInteractionSource() }
val enabled = true
val singleLine = true

BasicTextField(
    value = text,
    onValueChange = {text = it},
    interactionSource = interactionSource,
    enabled = enabled,
    singleLine = singleLine,
    modifier = Modifier.width(IntrinsicSize.Min)
) {
    TextFieldDefaults.OutlinedTextFieldDecorationBox(
        value = text,
        visualTransformation = VisualTransformation.None,
        innerTextField = it,
        singleLine = singleLine,
        enabled = enabled,
        interactionSource = interactionSource,
        // keep vertical paddings but change the horizontal
        contentPadding = TextFieldDefaults.textFieldWithoutLabelPadding(
            start = 8.dp, end = 8.dp
        ),
        colors = TextFieldDefaults.outlinedTextFieldColors()
    )
}

enter image description here

Note: it requires at least the compose version 1.2.0

  • Related