Text
如何使用 Jetpack Compose将文本与组件的底部对齐?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
aligns Text
insideBox
或Modifier.align(Alignment.BottomEnd)
in设置对齐对视图BoxScope
有什么android:layout_gravity
作用,对齐 Text 组件,而不是组件的内容,Text
您可以在difference
此处查看。
图像中蓝色矩形的代码是
@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
)
}
}
}