'Dense TextField in Jetpack Compose

In the old View system, we can make TextInputLayout dense using style Widget.MaterialComponents.TextInputLayout.FilledBox.Dense.

How can I create a dense variant of TextField in Compose?



Solution 1:[1]

Starting with 1.2.0-alpha04 you can use the TextFieldDecorationBox together with BasicTextField to build a custom text field based on Material Design text fields.

To create a dense text field, use contentPadding parameter to decrease the paddings around the input field.

Something like:

var text by remember { mutableStateOf("") }
val singleLine = true
val enabled = true
val interactionSource = remember { MutableInteractionSource() }
BasicTextField(
    value = text,
    onValueChange = { text = it },
    modifier = Modifier
        .indicatorLine(enabled, false, interactionSource, TextFieldDefaults.textFieldColors())
        .background(
            TextFieldDefaults.textFieldColors().backgroundColor(enabled).value,
            TextFieldDefaults.TextFieldShape
        )
        .width(TextFieldDefaults.MinWidth),
    singleLine = singleLine,
    interactionSource = interactionSource
) { innerTextField ->
    TextFieldDecorationBox(
        value = text,
        innerTextField = innerTextField,
        enabled = enabled,
        singleLine = singleLine,
        visualTransformation = VisualTransformation.None,
        interactionSource = interactionSource,
        label = { Text("Label") },
        contentPadding = TextFieldDefaults.textFieldWithLabelPadding(
            start = 4.dp,
            end = 4.dp,
            bottom = 4.dp // make it dense
        )
    )
}

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriele Mariotti