Sparsh Dutta
Sparsh Dutta

Reputation: 2990

Align Textfield label to start of underbar using Jetpack Compose

By default the label of Textfield is not aligned with the start position of underbar. There seems to be some empty space before the label text.

This is how my Textfields look like:

My Textfields

I want the label of my textfield to be aligned to the start position of underbar. How do I achieve this?

Upvotes: 1

Views: 1521

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363985

With 1.0.0 (tested with 1.0.0-beta07) the TextField follows the Material guidelines and there isn't a built-in parameter to change this behaviour.
You should use a BasicTextField with some specific styling.

Otherwise you can use the drawBehind modifier:

val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()

val IndicatorUnfocusedWidth = 1.dp
val IndicatorFocusedWidth = 2.dp
val TextFieldPadding = 16.dp

val indicatorColor = if (isFocused) Color.Red else Color.Gray
val indicatorWidth = if (isFocused) IndicatorFocusedWidth else IndicatorUnfocusedWidth

TextField(
    value = text,
    onValueChange = {
        text = it },
    label={Text("Label")},
    interactionSource = interactionSource,
    modifier = Modifier
        .drawBehind {
            val strokeWidth = indicatorWidth.value * density
            val y = size.height - strokeWidth / 2
            drawLine(
                indicatorColor,
                Offset(TextFieldPadding.toPx(), y),
                Offset(size.width - TextFieldPadding.toPx(), y),
                strokeWidth
            )
        },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.Transparent,
        focusedIndicatorColor =  Transparent,
        unfocusedIndicatorColor = Transparent,
        disabledIndicatorColor = Transparent
    )
)

enter image description here

Upvotes: 3

Related Questions