Home > Enterprise >  Set max height for box available from parent minus other child element in android jetpack compose
Set max height for box available from parent minus other child element in android jetpack compose

Time:01-25

I have 2 boxes one of fixed aspect ratio 16/9 and I want to set 2nd box to be the size of the remaining space.

The box with an aspect ratio of 16/9 is at the bottom.

I want white part to be filled with magenta box

I want the white part to be filled with a magenta box of width max and height responsive.

Here is what I tried ->

@Composable
fun HomeScreen() {
    Box {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Bottom
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(IntrinsicSize.Max)
                        .background(color = Color.Magenta)
                )
                Box(
                    modifier = Modifier
                        .aspectRatio(16 / 9f)
                        .background(color = Color.Red)
                )
            }
        }
    }
}

@Preview(
    showBackground = true, name = "Light mode",
    uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL
)
@Preview(
    showBackground = true, name = "Night mode",
    uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL
)
@Composable
fun HomeScreenPreview() {
    HomeScreen()
}

CodePudding user response:

In cases like this, Modifier.weight should be used: with the default parameter fill = true it will force the view to take up all the height remaining after the other unweighted children.

Box(
    modifier = Modifier
        .fillMaxWidth()
        .weight(1f)
        .background(color = Color.Magenta)
)
Box(
    modifier = Modifier
        .aspectRatio(16 / 9f)
        .background(color = Color.Red)
)
  •  Tags:  
  • Related