Thr*_*ian 3 android android-jetpack-compose android-jetpack-compose-text
如何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,
)
Run Code Online (Sandbox Code Playgroud)
我想对齐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
在这里。
图像中蓝色矩形的代码是
@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
)
}
}
Run Code Online (Sandbox Code Playgroud)
对于橙色矩形
@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
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
2年后,我想我已经找到了这个问题的实际解决方案:对于您的文本可组合项,添加此修饰符:
.wrapContentHeight()
对于参数,您可以将其与底部对齐Alignment.Bottom
你可以尝试:
Text(
modifier = Modifier
.height(150.dp)
.wrapContentHeight(Alignment.Bottom)
,
text = "whooopla",
)
Run Code Online (Sandbox Code Playgroud)
使用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 ")
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3148 次 |
最近记录: |