Android Jetpack Compose:无法为 OutlinedTextField 设置背景颜色

Android Jetpack Compose: Can't set backgroundColor for OutlinedTextField

我是 Jetpack Compose 的新手,正在尝试将 backgroundColor 设置为 OutlinedTextField。

这是我的代码

fun MyTextField() {
    Column(Modifier
        .background(Color.Gray)
        .fillMaxSize()
        .padding(8.dp)
    ) {
        OutlinedTextField(
            value = "text",
            onValueChange = {},
            colors = TextFieldDefaults.outlinedTextFieldColors(
                backgroundColor = Color.White, // does not work
                unfocusedBorderColor = Color.Red,
                textColor = Color.Red
            ),
            // modifier = Modifier.background(Color.White) - works but not as I expected
        )
    }
}

backgroundColor = Color.White 根本不起作用。 OutlinedTextField 保持透明:

当使用 modifier 时,背景发生了变化,而且还保留了标签的部分,即使我没有标签:

知道我做错了什么吗?谢谢。

我会在这里留下我的答案,因为我没有找到更简单的方法...

您可以定义一个可用作包装器+背景的可组合项。

@Composable
fun OutlinedTextFieldBackground(
    color: Color,
    content: @Composable () -> Unit
) {
    // This box just wraps the background and the OutlinedTextField
    Box {
        // This box works as background
        Box(
            modifier = Modifier
                .matchParentSize()
                .padding(top = 8.dp) // adding some space to the label
                .background(
                    color, 
                    // rounded corner to match with the OutlinedTextField
                    shape = RoundedCornerShape(4.dp) 
                )
        )
        // OutlineTextField will be the content...
        content()
    }
}

然后你只需要用它包裹你的OutlinedTextField

OutlinedTextFieldBackground(Color.LightGray) {
    OutlinedTextField(
        modifier = Modifier.fillMaxWidth(),
        value = textState.value,
        onValueChange = { textState.value = it },
        label = {
            Text(
                text = "Name"
            )
        },
    )
}

结果如下:

如您所见,它有效。但正如 Sergey Krivenkov 所提到的,就设计而言,这可能是一个糟糕的选择,因为标签的一半有一个背景而另一部分有另一个背景,这看起来很奇怪。

我找到了这个

Row(
        Modifier
            .background(
                colorResource(id = R.color.col_EEEEEE)
            )
            .align(BottomEnd)
            .padding(10.dp)
    ) {
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp, end = 20.dp).background(Color.White, RoundedCornerShape(22.dp)),
            shape = RoundedCornerShape(22.dp),
            value = "",
            onValueChange = {},
            textStyle = MaterialTheme.typography.caption
        )
    }

在上面的代码中,我在修饰符中添加了所需的背景颜色和形状。修饰符形状 属性 与 OutlinedTextField 形状 属性 相同,可提供所需的效果。