3

Is there a way to customise, (I would like to shorten the length) of the focussed indicator line on a TextField in Android Compose UI?

I know it's possible to hide it by setting the focusedIndicatorColor to Transparent as per example below:

TextField(
    value = ...,
    onValueChange = { ... },
    label = { Text("...") },
    modifier = Modifier.weight(1f).padding(horizontal = 8.dp, vertical = 6.dp),
    shape = RoundedCornerShape(8.dp),
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.LightGray,
        cursorColor = Color.Black,
        disabledLabelColor = Color.LightGray,
        focusedIndicatorColor = Color.Transparent,
        unfocusedIndicatorColor = Color.Transparent
    )
)
Calvin
  • 423
  • 3
  • 12

2 Answers2

3

The TextField follows the Material guidelines and there isn't a built-in parameter to change this behaviour.

You can use a workaround using the drawWithContent modifier:

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

val TextFieldPadding =  6.dp //use this value to change the length of th e indicator
val indicatorColor =  Color.Red
val indicatorWidth = 1.dp

TextField(
    value = text,
    onValueChange = {
        text = it },
    label={Text("Label")},
    interactionSource = interactionSource,
    modifier = Modifier
        .drawWithContent {
            drawContent()
            if (isFocused) {
                val strokeWidth = indicatorWidth.value * density
                val y = size.height - strokeWidth / 2
                drawLine(
                    indicatorColor,
                    Offset((TextFieldPadding).toPx(), y),
                    Offset(size.width - TextFieldPadding.toPx(), y),
                    strokeWidth
                )
            }
        },
    shape = RoundedCornerShape(8.dp),
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.LightGray,
        cursorColor = Color.Black,
        focusedIndicatorColor =  Transparent,
        unfocusedIndicatorColor = Transparent,
        disabledIndicatorColor = Transparent
    )
)

unfocused: enter image description here.

Focused: enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

You could try Modifier.indication() perhaps. I'm not really sure if it would work.

Modifier.indication( interactionSource = MutableInteractionSource(), indication = yourCustomIndicator )

Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42