如何创建带下划线、没有任何背景或边框的 TextField?

How to create a TextField with underbar, without any background or border?

我正在尝试在 Jetpack 中创建一个带有下划线但没有任何其他边框或背景的 TextField。我该怎么做?

这是我目前使用的代码:

val query = remember {mutableStateOf("")}
        TextField(
        value = query.value,
            onValueChange = { newValue -> query.value = newValue },
            label={Text("Dummy", color = colorResource(id = R.color.fade_green))},
            textStyle = TextStyle(
                textAlign = TextAlign.Start,
                color = colorResource(id = R.color.fade_green),
                fontFamily = FontFamily(Font(R.font.poppins_regular)),
                fontSize = 14.sp,
            ),
            modifier = Modifier
                .padding(start = 30.dp).border(0.dp, Color.Red),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent
            )
            )

对于 1.0.0 你可以只使用:

var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = {
        text = it
    },
    label = { Text("label") },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.Transparent,
        //Color of indicator = underbar
        focusedIndicatorColor = ....,
        unfocusedIndicatorColor = ....,
        disabledIndicatorColor = ....
    )
)

如果要更改 indicatorWidth 目前没有内置参数。

您可以使用 .drawBehind 修饰符来画线。类似于:

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

val indicatorColor = if (isFocused) Color.Red else Color.Gray
val indicatorWidth = 4.dp

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(0f, y),
                Offset(size.width, y),
                strokeWidth
            )
    },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.Transparent,
        focusedIndicatorColor =  Transparent,
        unfocusedIndicatorColor = Transparent,
        disabledIndicatorColor = Transparent
    )
)