Centering Text in Jetpack Compose

dan*_*elp 3 android android-jetpack-compose

I am trying to center the content inside a Text of Jetpack Compose, but I'm not succeeding. The code seems fine to me (I'm very new to Compose though). The code:

Row(
        modifier = Modifier
            .padding(8.dp)
            .height(30.dp)
            .fillMaxHeight(),
    ) {
        IconButton(..) {..}
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = "Some text",
            textAlign = TextAlign.Center,
            modifier = Modifier
                .fillMaxHeight()
                .border(1.dp, Color.Black, RoundedCornerShape(20))
                .width(120.dp)
                .background(color = Color.White, RoundedCornerShape(20))
                .align(Alignment.CenterVertically)
        )
        Spacer(modifier = Modifier.width(4.dp))
        IconButton(..) {..}
    }
Run Code Online (Sandbox Code Playgroud)

This yields the following result: 在此输入图像描述

Phi*_*hov 5

Text根据您的修改器获取完整高度,在这种情况下.align(Alignment.Center)对您没有帮助。

您可以将其放在Texta 内部Box并将其居中:

Row(
    modifier = Modifier
        .padding(8.dp)
        .height(30.dp)
        .fillMaxHeight()
) {
    IconButton({ }) { Text("hello ") }
    Spacer(modifier = Modifier.width(4.dp))
    Box(
        Modifier
            .fillMaxHeight()
            .border(1.dp, Color.Black, RoundedCornerShape(20))
            .width(120.dp)
            .background(color = Color.White, RoundedCornerShape(20))
    ) {
        Text(
            text = "Some text",
            textAlign = TextAlign.Center,
            modifier = Modifier
                .align(Alignment.Center)
        )
    }

    Spacer(modifier = Modifier.width(4.dp))
    IconButton({ }) { Text("hello ") }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过向文本添加填充来解决此问题,但在这种情况下,您无法Row显式指定高度,并且需要让它包裹内容大小:

Row(
    verticalAlignment = Alignment.CenterVertically,
    modifier = Modifier
        .padding(8.dp)
) {
    IconButton({ }) { Text("hello ") }
    Spacer(modifier = Modifier.width(4.dp))
    Text(
        text = "Some text",
        textAlign = TextAlign.Center,
        modifier = Modifier
            .border(1.dp, Color.Black, RoundedCornerShape(20))
            .width(120.dp)
            .background(color = Color.White, RoundedCornerShape(20))
            .padding(vertical = 10.dp)
    )
    Spacer(modifier = Modifier.width(4.dp))
    IconButton({ }) { Text("hello ") }
}
Run Code Online (Sandbox Code Playgroud)

  • 我明白你在做什么,但这似乎是一个解决方法。在我看来,在不使用额外的 Compose 元素的情况下无法将 _text_ 置于 `Text` 中是非常奇怪的。 (3认同)