Box - devrath/ComposeAlchemy GitHub Wiki

Need of box composable

  • Consider you have a composable and there are 2 children --> Here the composables are placed one above another
  • But the catch is that We cannot arrange them in the position w.r.t to the container.
  • As a solution we have box composable

Example

  • Here we can place an image and view the heart icon on the bottom right of the image & top of the image.

Code

@Composable
fun BoxDemoScreen(modifier: Modifier = Modifier) {

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Box(
            contentAlignment = Alignment.BottomEnd // We can put the alignment in the parent
        ) {
            // First Position = Image
            Image(
                painter = painterResource(R.drawable.pikachu),
                contentDescription = "Background Image"
            )
            // Second Position = Gradient on top of image
            Box(
                modifier = Modifier
                    .matchParentSize() // Special modifier that matches to the parent content
                    .background(
                        // We can add the gradient here
                        brush = Brush.verticalGradient(
                            colors = listOf(Color.Transparent, Color.Magenta)
                        )
                    )
            )
            // Third position = icon on top of both Image and Gradient
            Icon(
                modifier = Modifier.align(alignment = Alignment.BottomCenter),// Individually we can add the alignment
                imageVector = Icons.Default.Star,
                contentDescription = "Star"
            )
        }
    }
}

Out-put