deja
deja

Reputation: 526

How to change TextField's indicator width in Jetpack Compose?

I've been wondering if there is a way to change TextField's indicator (underline) width.

Upvotes: 1

Views: 1077

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364740

There isn't a parameter to achieve it since TextField follows the Material guidelines.

You can use a custom modifier to draw a line at the bottom of the TextField:

fun Modifier.drawCustomIndicatorLine(
    indicatorBorder: BorderStroke,
    indicatorPadding : Dp = 0.dp
): Modifier {

    val strokeWidthDp = indicatorBorder.width
    return drawWithContent {
        drawContent()
        if (strokeWidthDp == Dp.Hairline) return@drawWithContent
        val strokeWidth = strokeWidthDp.value * density
        val y = size.height - strokeWidth / 2
        drawLine(
            indicatorBorder.brush,
            Offset((indicatorPadding).toPx(), y),
            Offset(size.width - indicatorPadding.toPx(), y),
            strokeWidth
        )
    }
}

Then use it and apply a Transparent color to hide the default Indicator.

Something like:

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

val indicatorColor =  if (isFocused) Color.Red else Teal200

TextField(
    value = text,
    onValueChange = { text = it },
    interactionSource = interactionSource,
    modifier = Modifier.drawCustomIndicatorLine(
        indicatorBorder = BorderStroke(1.dp,indicatorColor),
        indicatorPadding = 10.dp
    ),
    shape = RoundedCornerShape(8.dp),
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.LightGray,
        cursorColor = Color.Black,
        focusedIndicatorColor =  Transparent,
        unfocusedIndicatorColor = Transparent,
        disabledIndicatorColor = Transparent
    )
)

enter image description here

Upvotes: 1

Related Questions