The last post from me of 2021. I have been delving deeper into Android Jetpack Compose and wanted to create some tutorial posts.

For this tutorial, we will be looking at the Spacer component.

What is Spacer?


The Spacer component is used to display an empty space. Width and (or) height can be set for Spacer using Modifier object.

@Composable
fun Spacer() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
                    .background(Color.Green)
            )
        }
    }
}

Here I have created a composable that shows a green box. Contained in a column and row.




Let’s see what happens when we add another box to the composable.

@Composable
fun Spacer() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
                    .background(Color.Green)
            )

            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
                    .background(Color.Red)
            )
        }
    }
}

Awesome. We now have a Green and Red box displaying on our screen.




It looks good but not quite what we want. Let’s use Spacer to create a gap between the green and red boxes.

@Composable
fun Spacer() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
                    .background(Color.Green)
            )
            Spacer(modifier = Modifier.width(50.dp))
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
                    .background(Color.Red)
            )
        }
    }
}

Adding the Spacer component has given us a nice gap between the green and red boxes.

Let's See It in Action




Russell Morley

Test Lead | Software Developer In Test | Automation Enthusiast