如何将文本与 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
设置对齐方式对齐 Text
里面 Box
或 Modifier.align(Alignment.BottomEnd)
在 BoxScope
做什么android:layout_gravity
用于 View ,对齐文本组件,不是内容的 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
)
}
}
}
最佳答案
使用 align
修饰符,您可以将子组件相对于其父组件对齐在特定位置:
Box(modifier = Modifier.fillMaxSize()) {
Text(modifier = Modifier.align(Alignment.BottomEnd),text = "Aligned to bottom end")
Text(modifier = Modifier.align(Alignment.BottomStart),text = "Aligned to bottom start")
Text(modifier = Modifier.align(Alignment.CenterStart),text = "Aligned to start center ")
Text(modifier = Modifier.align(Alignment.TopCenter),text = "Aligned to top center ")
}
关于android - Jetpack Compose 如何将特定大小的文本组件的文本或内容与左下角或右下角对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66303328/