如何在 Jetpack Compose 中将视图的基线与另一个视图的顶部对齐?

2024-03-07

我有一个卡片视图,我想将另一个视图(图中的红色视图)的中心与卡片的顶部对齐,如图所示。

我该怎么做?卡的代码是这样的:

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 inside 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)
        )
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Jetpack Compose 中将视图的基线与另一个视图的顶部对齐? 的相关文章

随机推荐