Jetpack Compose TextField 深色模式下的文本颜色

Bar*_*ine 11 android android-jetpack-compose android-darkmode android-compose-textfield

我一直在尝试 Jetpack compose,我注意到,尽管Text切换到深色模式时文本颜色会正确更新,但TextField或 的文本颜色OutlinedTextField仍然顽固地保持黑色。不过,标签和提示的颜色正确。

确定字段的默认文本样式是MaterialTheme.typography.body1我已更新我的应用程序主题以包含此解决方法:

val typography = if (darkTheme) {
    //TODO: Hack to show text field text in dark mode
    MaterialTheme.typography.copy(body1 = MaterialTheme.typography.body1.copy(color = Color.White))
} else {
    MaterialTheme.typography
}
MaterialTheme(colors = colors, content = content, typography = typography)
Run Code Online (Sandbox Code Playgroud)

但如果这是解决方案,我就必须对每种排版风格都这样做,而且感觉应该是自动的。那么我是否做错了什么,或者这是在正式发布之前将得到解决的问题之一?

这是我的实际可组合项之一(包含在我的主题中):

@Composable
fun UsernameField(
    value: String,
    isError: Boolean,
    onValueChange: (String) -> Unit,
) {
    Column {
        OutlinedTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier.fillMaxWidth(),
            label = { Text("Username") },
            isError = isError,
            trailingIcon = {
                ClearIcon(
                    visible = value.isNotEmpty(),
                    onClick = { onValueChange("") }
                )
            }
        )
        Text(
            if (isError) "Minimum 6 characters" else "",
            style = MaterialTheme.typography.caption,
            color = MaterialTheme.colors.error,
            modifier = Modifier.padding(top = 4.dp)
        )
    }
}

@Composable
fun ClearIcon(visible: Boolean, onClick: () -> Unit) {
    if (visible) IconButton(onClick = onClick) {
        Icon(
            imageVector = Icons.Filled.Cancel,
            contentDescription = "Clear username",
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 15

尝试用 Surface 包装它/将 Surface 应用到使用的可组合项中UsernameField。简而言之,您没有适当的背景,文本可以在该背景上采取适当的颜色配置来进行对比。

有一个可能的行为和修复的简短示例:

@Preview
@Composable
fun DarkModeTest() {
    MaterialTheme(darkColors()) {
        Column {
            Surface {
                OutlinedTextField(value = "good", onValueChange = {})
            }
            OutlinedTextField(value = "bad", onValueChange = {})
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

简单的例子

通过查看文档:

Surface 负责:

...

内容颜色:Surface 使用 contentColor 指定该表面内容的首选颜色 - 文本和图标组件将其用作默认颜色。