0

有没有办法自定义,(我想缩短长度)在 Android Compose UI 中的 TextField 上的焦点指示线?

我知道可以通过将其设置focusedIndicatorColor为透明来隐藏它,如下例所示:

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
    )
)
4

2 回答 2

1

遵循材料指南,TextField并且没有内置参数可以更改此行为。

您可以使用drawWithContent修饰符使用解决方法:

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
    )
)

不专心: 在此处输入图像描述

重点: 在此处输入图像描述

于 2021-08-02T19:52:20.293 回答
0

或许你可以试试Modifier.indication()。我不确定它是否会起作用。

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

于 2021-08-02T19:48:50.957 回答