android - 如何在 Jetpack Compose 中将视图的基线与另一个视图的顶部对齐?
问题描述
我有一个卡片视图,我想将另一个视图(图片中的红色视图)的中心对齐到卡片的顶部,就像图片中一样。
我该怎么做?卡的代码是这样的:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CardDemo()
}
}
}
@Composable
fun CardDemo() {
Column(
modifier = Modifier.fillMaxSize().background(Color.LightGray),
verticalArrangement = Arrangement.Center) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
elevation = 10.dp,
) {
Column(
modifier = Modifier.padding(15.dp)
) {
Text("Card Title")
Text("Card Subtitle")
Text("Card Content Line 1")
Text("Card Content Line 2")
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
ComposeDemoTheme {
CardDemo()
}
}
解决方案
你应该使用Box
你需要你的覆盖视图在上面,Card
否则它会被剪切,所以放在Card
里面Box
。你也可以使用offset
修饰符来移动你的视图:
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray),
verticalArrangement = Arrangement.Center
) {
Box(Modifier.padding(15.dp)) {
val textPadding = 15.dp
val overlayBoxHeight = 20.dp
Card(
elevation = 10.dp,
modifier = Modifier
.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(textPadding)
) {
Text("Card Title")
Text("Card Subtitle")
Text("Card Content Line 1")
Text("Card Content Line 2")
}
}
Box(
Modifier
.height(overlayBoxHeight)
.width(40.dp)
.offset(x = textPadding, y = -overlayBoxHeight / 2)
.background(Color.Red)
)
}
}
推荐阅读
- java - LocalTime() 两次之间的差异
- c++ - 向用户询问指定数量的字符?
- php - 带日期的 CRUD(创建和读取)
- java - Java 应用程序无法在 Mac OSX Sierra 上启动
- python - 从表格中提取文本
- git - 在 master 中维护带有补丁的 fork
- javascript - 重新定义 javascript 类/对象构造函数以分配全局变量
- node.js - 无需等待连接“打开”事件即可导出 Mongoose 模型
- javascript - 从 PHP 到 Javascript 的正则表达式转换问题
- gdb - GDB - 在 gdb 和 OCD Deamon 之间建立通信