Android Compose Material3中OutlinedTextField颜色参数不生效
解决Material3中OutlinedTextField focusedLabelColor不生效的问题
问题根源:当你手动在label参数中传入自定义Text组件时,Text默认使用LocalContentColor.current作为文本颜色,会覆盖OutlinedTextFieldDefaults.colors中设置的focusedLabelColor。
解决方法一:让Text继承TextField的颜色状态
通过LocalTextFieldColors.current获取TextField当前的颜色配置,动态设置Text的颜色:
OutlinedTextField( label = { val textFieldColors = LocalTextFieldColors.current Text( text = "Label", // 根据TextField的启用/聚焦状态获取对应颜色 color = textFieldColors.labelColor( enabled = true, focused = LocalFocusManager.current.isFocused ).value ) }, colors = OutlinedTextFieldDefaults.colors( focusedLabelColor = Color.Blue, focusedTextColor = Color.Red ), value = "", onValueChange = {} )
解决方法二:移除自定义Text的固定颜色(仅当不需要额外Text样式时)
如果不需要给Text设置其他自定义样式,直接传入Text("Label")且不指定颜色,此时Text会自动应用OutlinedTextFieldDefaults.colors中的配置:
OutlinedTextField( label = { Text("Label") }, colors = OutlinedTextFieldDefaults.colors( focusedLabelColor = Color.Blue, focusedTextColor = Color.Red ), value = "", onValueChange = {} )
注:如果之前给Text手动设置了color参数,一定要移除,否则仍然会覆盖配置的颜色。
解决方法三:通过监听聚焦状态手动控制颜色
使用FocusRequester监听TextField的聚焦状态,直接给Text设置对应颜色:
val focusRequester = remember { FocusRequester() } val isFocused = remember { mutableStateOf(false) } OutlinedTextField( label = { Text( text = "Label", color = if (isFocused.value) Color.Blue else LocalContentColor.current ) }, colors = OutlinedTextFieldDefaults.colors( focusedTextColor = Color.Red ), value = "", onValueChange = {}, modifier = Modifier .focusRequester(focusRequester) .onFocusChanged { isFocused.value = it.isFocused } )
内容的提问来源于stack exchange,提问作者Inori
相关产品推荐
相关产品推荐

