在Jetpack Compose版本alpha-11中,我正在努力解决文本垂直居中的问题。我的字体似乎有大量的填充,我无法找到禁用它的方法。据我所知,这在here上只出现过一次,但他们使用约束布局的答案似乎表明,他们只是简单地将其定位在绝对位置,这与其说是一种解决方案,不如说是一种变通办法,也是我想要避免的。
你可以在下面的截图中清楚地看到它。

代码如下所示:
Column(verticalArrangement = Arrangement.Center) {
Text(
text = "Let's Go",
color = Color.White,
fontSize = 120.sp,
fontFamily = oswaldLightFontFamily(),
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Blue)
)
}您希望将其定位的参数-- verticalArrangement和textAlign --在这里没有任何作用,但我将它们包括进来是为了演示我所尝试的内容。
到目前为止,我的解决方法是使用Modifier.graphicsLayer(translationY = -25f)将其向上移动,但对于本应如此简单的东西来说,这似乎是一个可怕的技巧。似乎在经典的安卓布局中,一个人可以设置android:includeFontPadding="false",这样就可以绕过这个行为,但在Jetpack Compose中似乎没有类似的选项。
有没有人遇到过这种情况?
发布于 2021-08-01 17:22:31
根据https://issuetracker.google.com/issues/171394808的说法,这似乎是当前JetPack Compose的局限性之一。
这也破坏了我的应用程序,因为使用的字体严重依赖于includeFontPadding。对于当前的变通方法,我创建了一个将TextView包装在compose中的CoreText。
下面是我的包装器的例子,它并不完美,但它可以满足我当前的用例:
@Composable
fun CoreText(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
overflow: TextOverflow = TextOverflow.Clip,
maxLines: Int = Int.MAX_VALUE,
style: TextStyle = Typography.body2,
onClick: (() -> Unit)? = null,
) {
AndroidView(
modifier = modifier,
factory = { context ->
TextView(context)
},
update = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
it.setTextAppearance(style.fontWeight.toStyle())
} else {
it.setTextAppearance(it.context, style.fontWeight.toStyle())
}
if (overflow == TextOverflow.Ellipsis) {
it.ellipsize = TextUtils.TruncateAt.END
}
if (textDecoration != null) {
it.paintFlags = when (textDecoration) {
TextDecoration.Underline -> {
Paint.UNDERLINE_TEXT_FLAG
}
TextDecoration.LineThrough -> {
Paint.STRIKE_THRU_TEXT_FLAG
}
else -> 0
}
}
if (onClick != null) {
it.setOnClickListener { onClick.invoke() }
}
if (color != Color.Unspecified || style.color != Color.Unspecified) {
it.setTextColor(if (color == Color.Unspecified) style.color.toArgb() else color.toArgb())
}
it.textSize = style.fontSize.value
it.text = text
it.background = ColorDrawable(style.background.toArgb())
it.maxLines = maxLines
it.includeFontPadding = false
it.textAlignment = textAlign?.toStyle() ?: style.textAlign.toStyle()
}
)
}
// Replace with your style
fun FontWeight?.toStyle(): Int {
return when (this) {
FontWeight.Bold -> R.style.TextStyle_Bold
FontWeight.Normal -> R.style.TextStyle_Regular
FontWeight.Medium, FontWeight.SemiBold -> R.style.TextStyle_Medium
else -> -1
}
}
fun TextAlign?.toStyle(): Int {
return when (this) {
TextAlign.Left -> TEXT_ALIGNMENT_TEXT_START
TextAlign.Right -> TEXT_ALIGNMENT_TEXT_END
TextAlign.Center -> TEXT_ALIGNMENT_CENTER
TextAlign.Start -> TEXT_ALIGNMENT_TEXT_START
TextAlign.End -> TEXT_ALIGNMENT_TEXT_END
else -> -1
}
}发布于 2021-06-21 02:33:43
只是绕过了同样的问题。
Box(contentAlignment = Alignment.Center){
Text(
text = "OK"
textAlign = TextAlign.Center
)
}https://stackoverflow.com/questions/66126551
复制相似问题