如何在使用Jetpack Compose的
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
内部或者在BoxScope
中使用Modifier.align(Alignment.BottomEnd)
所做的与视图中使用android:layout_gravity
相同,会对齐Text
组件,而不是Text
组件的内容,您可以在此处查看差异。
图像中蓝色矩形的代码为:
@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
)
}
}
}
Text
组合元件的父元素是Box
(作为Column
或Row
的子元素将不能正常工作),则只有直接从align
修饰符访问才能起作用。 - Lucas Sousaandroid:layout_gravity
操作。我的问题是关于如何为文本组件执行android:layout_gravity
操作。我已经将橙色文本组件对齐到一个框内。但是这些文本有一个大小,我希望它们的内容在其中对齐,这可以通过类Views中的android:gravity
完成。这里的答案解释了区别。 - Thracian