Search code examples
androidandroid-jetpack-composetextfieldandroid-compose-textfield

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?


Solution

  • 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