You have been able to use the Column and Row Composables to arrange Composables vertically and horizontally respectively.
However, you may have noticed that the items within a Column or Row Composable are very close together.
In order to define the spacing between items within a Column or Row Composable, we can use the Spacer Composable.
The Spacer Composable is a Composable that is used to add space between Composables.
This Composable contains only 1 parameter:
-
modifier: This is used to modify theSpacerComposable. It is of typeModifierand has a default value ofModifier.
This Composable is very useful when we want to add space between Composables within a Column or Row Composable.
Spacer
Let us add some space between our Image and Text Composables in the FoodCategoryItem component.
Currently, the Image and Text Composables are separated using a top padding Modifier on the Text Composable. There is a much cleaner way for us to do this.
Column(
modifier = Modifier.size(75.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
modifier = Modifier.size(75.dp),
painter = painterResource(id = icon),
contentDescription = null
)
// Add a 5.dp spacer between the image and the text
Spacer(modifier = Modifier.size(5.dp))
// remove the top padding from the text
Text(
modifier = Modifier,
text = category,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.bodyMedium
)
}
Weight
The weight Modifier function is used to specify how much space an item should take up within a Column or Row Composable.
Weight is specified as a Float value with the default value is 1f.
The weight of an item is relative to the weight of other items within the Column or Row Composable.
For example, if we have 2 items within a Column Composable, and we set the weight of the first item to 1f and the weight of the second item to 2f, the second item will take up twice as much space as the first item.
Weight
Row(modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalAlignment = Alignment.Top) {
Text(text = "Hello World", modifier = Modifier.weight(2f))
Spacer(modifier = Modifier.weight(1f))
Text(text = "Hello Columns", modifier = Modifier
.weight(1f))
Text(text = "Hello Columns", modifier = Modifier
.weight(1f))
}
Conclusion
In this session, you learned how to use the Spacer Composable to add space between Composables. You also learned how to use the weight Modifier function to specify how much space an item should take up within a Column or Row Composable.
In our next session, we will start to understand how we can organize our code into different files and packages for a Jetpack Compose project.