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

问题描述

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

这是我目前使用的代码

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-beta04,您可以只使用:

var text by remember { mutableStateOf(TextFieldValue("")) }

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

enter image description here enter image description here

如果您想更改 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,strokeWidth
            )
    },focusedIndicatorColor =  Transparent,unfocusedIndicatorColor = Transparent,disabledIndicatorColor = Transparent
    )
)

enter image description here