当OutlinedTextField不在焦点上时,是否有办法将OutlinedTextField的标签放在顶部(展开)并仍保留占位符?在xml布局中,我们有TextInputLayout,它有expandedHintEnabled属性来执行扩展。
ktecyv1j1#
目前,placeholder应用alpha修饰符,条件为InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f,但没有参数可实现与expandedHintEnabled相同的行为。解决方法是使用visualTransformation在文本为空时显示占位符,并删除placeholder参数。比如:
placeholder
alpha
InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f
expandedHintEnabled
visualTransformation
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) }
1条答案
按热度按时间ktecyv1j1#
目前,
placeholder
应用alpha
修饰符,条件为InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f
,但没有参数可实现与expandedHintEnabled
相同的行为。解决方法是使用
visualTransformation
在文本为空时显示占位符,并删除placeholder
参数。比如:
与: