How to align a view's baseline to another view's top in Jetpack Compose?

Viewed 1285

I have a Card view and I want to align another view (Red view in picture)'s center to top of the Card like in the picture.

How do I do it? The code for the Card is like this:

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()
    }
}
1 Answers

You should use Box

You need your overlay view be on top of Card otherwise it'll be cut, so place Card inside Box. Also you can use offset modifier to move your view:

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)
        )
    }
}

Related