相当于 Jetpack Compose TextField 中的“expandedHintEnabled”

问题描述 投票:0回答:1

当 OutlinedTextField 不处于焦点时,有什么方法可以将 OutlinedTextField 的标签放在顶部(展开)并且仍然具有占位符?

在 xml 布局中,我们有 TextInputLayout,它具有 expandedHintEnabled 属性来进行扩展。

android kotlin android-jetpack-compose android-textinputlayout android-compose-textfield
1个回答
2
投票

目前

placeholder
在这种条件
alpha
下应用
InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f
修饰符,并且没有参数来实现与
expandedHintEnabled
相同的行为。

解决方法可以是在文本为空时使用

visualTransformation
显示占位符,删除
placeholder
参数。

类似:

    val textColor = if (text.isEmpty())
        MaterialTheme.colors.onSurface.copy(ContentAlpha.medium)
    else
        LocalContentColor.current.copy(LocalContentAlpha.current)

    val textStyle = if (text.isEmpty())
        LocalTextStyle.current.merge(MaterialTheme.typography.subtitle1)
    else
        LocalTextStyle.current

    TextField(
        value = text,
        onValueChange = { text = it },
        //placeholder = { Text("Placeholder") },
        label = { Text("Label") },
        visualTransformation = if (text.isEmpty())
            PlaceholderTransformation("Placeholder")
        else VisualTransformation.None,
        textStyle = textStyle,
        colors = TextFieldDefaults.textFieldColors(
            textColor = textColor
        )
    )

与:

class PlaceholderTransformation(val placeholder: String) : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        return PlaceholderFilter(text, placeholder)
    }
}

fun PlaceholderFilter(text: AnnotatedString, placeholder: String): TransformedText {

    val numberOffsetTranslator = object : OffsetMapping {
        override fun originalToTransformed(offset: Int): Int {
            return 0
        }

        override fun transformedToOriginal(offset: Int): Int {
            return 0
        }
    }

    return TransformedText(AnnotatedString(placeholder), numberOffsetTranslator)
}
© www.soinside.com 2019 - 2024. All rights reserved.