我如何在Jetpack Compose中实现与textAllCaps
相同的效果?我知道可以使用toUpperCase
方法将字符串转换为大写字母,但我想知道是否有属性可以添加到Text
组件中,以使文本在视觉上呈现为大写字母?
Text(
text = stringResource(id = R.string.app_name).toUpperCase(Locale.current)
)
我如何在Jetpack Compose中实现与textAllCaps
相同的效果?我知道可以使用toUpperCase
方法将字符串转换为大写字母,但我想知道是否有属性可以添加到Text
组件中,以使文本在视觉上呈现为大写字母?
Text(
text = stringResource(id = R.string.app_name).toUpperCase(Locale.current)
)
@Composable
fun CapsText(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
Text(
text = text.uppercase(),
modifier = modifier,
color = color,
fontSize = fontSize,
fontStyle = fontStyle,
fontWeight = fontWeight,
fontFamily = fontFamily,
letterSpacing = letterSpacing,
textDecoration = textDecoration,
textAlign = textAlign,
lineHeight = lineHeight,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
onTextLayout = onTextLayout,
style = style,
)
}
Text(
text = stringResource(id = R.string.app_name).uppercase()
)
您可以在stringResource
上添加.uppercase()
。
目前我正在使用compose 1.2.0-beta03
版本。
.toUpperCase(Locale.current) 已被弃用,应使用 .uppercase() 替代。 以下是使用示例:
Text(
text = ("any").uppercase()
)
这将作为“任何”在用户界面中呈现。
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Characters
)
您可以始终使用 String 类的 capitalize 函数。另外,Text 组合也可以将 Annotated String 作为输入,您可以使用 AnnotatedString 的 toUpperCase 函数:
@Preview(showBackground = true)
@Composable
fun Sample() {
Text(text = upperCased("Hello"))
}
@Composable
fun upperCased(input: String): AnnotatedString {
return buildAnnotatedString {
append(input)
// You can also add styling here as below:
//
// withStyle(style = SpanStyle(color = Color.Blue)) {
// append("John")
// }
// append("Doe")
//
// withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
// append("W")
// }
// append("orld")
}.toUpperCase()
}
Text(
stringResource(id = R.string.main_widget)**.toUpperCase(Locale.getDefault())**,
fontFamily = aeonikPro,
fontWeight = FontWeight.Medium,
color = ColorGraySecondary,
fontSize = 20.sp
)
Text
组合有两个版本:一个接受String
,另一个接受AnnotatedString
。我觉得你的修改没有意义,所以我要回滚它。 - Phil Dukhov