如何更改Jetpack Compose BasicTextField的文本颜色?

13
我正在尝试使用BasicTextField创建搜索栏。
默认的文字颜色是黑色,我找不到任何选项来更改文字颜色。
此外,我需要更改文字大小、字体和其他属性。
@Composable
fun MyBasicTextField(){
    var text by remember { mutableStateOf("Hello") }
    BasicTextField(
        value = text,
        onValueChange = {
            text = it
        },
        decorationBox = { ... },
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.DarkGray, CircleShape)
            .padding(10.dp)
    )
}

Jetpack Compose基本文本框

如果使用 BasicTextField 不可行,是否有其他方法创建类似的视图?
我已经尝试使用 TextField,但存在一些问题,如删除标签、高度、背景等。

3个回答

18
你需要使用 textStyle 参数。如果你想使用默认文本样式,可以使用 LocalTextStyle
BasicTextField(
    // ...
    textStyle = LocalTextStyle.current.copy(color = Color.White)
)

或者您可以使用其中一种 Material 风格:

BasicTextField(
    // ...
    textStyle = MaterialTheme.typography.body1.copy(color = Color.White)
)

6

如果您想使用当前的 Material 主题颜色,以便它适应浅色和深色主题,则还需要使用 LocalContentColor.current

val localStyle = LocalTextStyle.current
val mergedStyle = localStyle.merge(TextStyle(color = LocalContentColor.current))
BasicTextField(
    textStyle = mergedStyle,
    cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
)

你可能也想把光标画笔的颜色从默认的黑色改变。经过一番搜索,我发现TextField使用主要颜色(至少在Material 3中)。


4
除了其他答案,这个对我有用,在添加 textStyle 属性时:
textStyle = TextStyle(
                        color = Color.White, 
                        fontFamily = FontFamily.SansSerif,
                        fontSize = 14.sp,
                        textAlign = TextAlign.Center,
                    )

这里是您可以设置的所有TextStyle属性:

https://developer.android.com/reference/kotlin/androidx/compose/ui/text/TextStyle

public constructor TextStyle(
        color: Color,
        fontSize: TextUnit,
        fontWeight: FontWeight?,
        fontStyle: FontStyle?,
        fontSynthesis: FontSynthesis?,
        fontFamily: FontFamily?,
        fontFeatureSettings: String?,
        letterSpacing: TextUnit,
        baselineShift: BaselineShift?,
        textGeometricTransform: TextGeometricTransform?,
        localeList: LocaleList?,
        background: Color,
        textDecoration: TextDecoration?,
        shadow: Shadow?,
        textAlign: TextAlign?,
        textDirection: TextDirection?,
        lineHeight: TextUnit,
        textIndent: TextIndent?
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接