首页 > 解决方案 > 如何在 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()
    }
}

标签: androidkotlinandroid-jetpack-compose

解决方案


你应该使用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)
        )
    }
}


推荐阅读