【发布时间】:2021-02-21 14:26:58
【问题描述】:
如何使用 Jetpack Compose 将文本与 Text 组件的底部对齐? TextAlign 只有Start、End、Left、Center、Right 和Justify 选项。
Text(
text = "First",
textAlign = TextAlign.Start,
modifier = Modifier
.background(Color(0xFF1976D2))
.size(200.dp),
color = Color.White,
)
我想对齐Text 组件的内容,每个Text 都有特定的大小 使用modifier.size(x),将它们的文本对齐到底部。在图像中,蓝色矩形是Text,大小不同,应该像在经典Android 中使用android:gravity 一样对齐其中的文本。
它类似于textAlign = TextAlign.x,但用于底部。
从Box 设置对齐方式将Text 内Box 或Modifier.align(Alignment.BottomEnd) 内BoxScope 执行android:layout_gravity 对视图执行的操作,对齐文本组件,不是内容 Text 组件,你可以看到difference here。
图像中蓝色矩形的代码是
@Composable
fun BoxExample() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.background(Color.LightGray)
) {
// This is the one at the bottom
Text(
text = "First",
modifier = Modifier
.background(Color(0xFF1976D2))
.size(200.dp),
color = Color.White,
)
// This is the one in the middle
Text(
text = "Second",
modifier = Modifier
.background(Color(0xFF2196F3))
.size(150.dp),
color = Color.White
)
// This is the one on top
Text(
text = "Third ",
modifier = Modifier
.background(Color(0xFF64B5F6))
.size(100.dp),
color = Color.White
)
}
}
对于橙色矩形
@Composable
fun BoxShadowAndAlignmentExample() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.background(Color.LightGray)
.padding(8.dp)
) {
Box(
modifier = Modifier.shadow(
elevation = 4.dp,
shape = RoundedCornerShape(8.dp)
)
) {
// This is the one at the bottom
Text(
text = "First",
modifier = Modifier
.background(Color(0xFFFFA000))
.size(200.dp),
color = Color.White
)
}
Box(
modifier = Modifier.shadow(
elevation = 4.dp,
shape = RoundedCornerShape(8.dp)
)
.align(Alignment.TopEnd)
) {
// This is the one in the middle
Text(
text = "Second",
modifier = Modifier
.background(Color(0xFFFFC107))
.size(150.dp),
color = Color.White
)
}
val modifier = Modifier.shadow(
elevation = 4.dp,
shape = RoundedCornerShape(8.dp)
)
.align(Alignment.BottomStart)
Box(
modifier = modifier
) {
// This is the one on top
Text(
text = "Third ",
modifier = Modifier
.background(Color(0xFFFFD54F))
.size(100.dp),
color = Color.White
)
}
}
}
【问题讨论】:
标签: android android-jetpack-compose android-jetpack-compose-text