android 等效于Jetpack合成文本字段中的“expandedHintEnabled”

fdx2calv  于 2023-02-02  发布在  Android
关注(0)|答案(1)|浏览(134)

当OutlinedTextField不在焦点上时,是否有办法将OutlinedTextField的标签放在顶部(展开)并仍保留占位符?
在xml布局中,我们有TextInputLayout,它有expandedHintEnabled属性来执行扩展。

ktecyv1j

ktecyv1j1#

目前,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 {

    var out = placeholder

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

相关问题