Jetpack Compose. Base Layouts
Today I am starting a series of articles to enter building android applications using jetpack compose. In this article, we will learn what are the basic layouts and learn how to use them.
If we do not indicate how to place the widgets, then they will be drawn on top of each other:
@Composable
fun MainScreen() {
Text("Morgan")
Text("23 yo")
}
As a result, we will see this:
In order to correctly position the elements on the screen, we must show how to do this. There are many ways to do this, the basic ones are: Column, Row, Box. Let’s take a look at each of them and start with Column and Row.
Column and Row are used to arrange items in a vertical and horizontal list, respectively:
@Composable
fun MainScreen() {
Column {
Row {
Image(
painter = painterResource(R.drawable.ic_baseline_android_24),
contentDescription = "Avatar"
)
Column {
Text("Morgan")
Text("23 yo")
}
}
}
}
Using a Column and an Image within a Row so that they appear side by side as one item. If we run the code now, we will see the following:
The markup has floated, apparently, in addition to specifying how to arrange the elements on the screen, we also need to indicate the location of the markup elements.
The @Composable elements that we used above have the ability to set display parameters, in the case of Column and Row we can set parameters for vertical and horizontal arrangement of elements:
@Composable
fun MainScreen() {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Image(
painter = painterResource(R.drawable.ic_baseline_android_24),
contentDescription = "Avatar"
)
Column(modifier = Modifier.padding(horizontal = 8.dp)) {
Text("Morgan")
Text("23 yo")
}
}
}
By hardcoded alignment, we tell the system how the screen element should look. In addition to alignment, we also used Modifier, which allows you to customize the widget to which it is applied, for example, by specifying the size and padding. The element now looks like this: