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)
您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)

| 归档时间: |
|
| 查看次数: |
7700 次 |
| 最近记录: |