问题描述
如何使用 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,)
我想将文本左下角或右下角对齐,如何使用 Jetpack Compose 来实现?
可以对齐它的元素,但我想对齐 Text
组件,每个 具有特定大小 以将其文本对齐到底部。在图像中,不同大小的蓝色矩形应该像在经典 Android 中一样对齐它们内部的文本,并使用 android:gravity
完成。
我真正想要的是类似于 textAlign = TextAlign.x
但对于底部。
从框设置对齐方式会像 android:layout_gravity
一样对齐框内的文本,您可以看到 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),)
// 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 ")
}
,
假设您的组件是一个 Box,将您的文本放在 Box 中,如下所示:
Box(
modifier = Modifier.fillMaxSize(),Alignment.BottomStart
) {
Text(
"First",Modifier.padding(16.dp),)
}
基本上,您定义要在该组件中使用的组件部分,而不是在文本中。