![]() |
VOOZH | about |
ConstraintLayout is the view system in a ViewGroup to place widgets relative to the position of other widgets on the screen. In jetpack compose, almost every layout can be created using Rows and Columns but if you want to create larger complicated Layouts you can also use Constraint Layout as an alternative to Rows and Columns. In this article, we are gonna create a simple Layout that demonstrates the use of ConstraintLayout in Jetpack Compose. First, grab the image from here or use any Image of your choice. We will be creating this layout. Let's look at the step-by-step guide.
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Note: Select Kotlin as the programming language.
Open build.gradle.kts (Module: app) and add the following dependency.
dependencies {
...implementation ("androidx.constraintlayout:constraintlayout-compose:1.0.1")
}
Create a Composable function named ConstraintLayoutExample. In Jetpack Compose we have Composable named ConstraintLayout in which we can put our other composable to position it relative to others.
In Compose we use createRefs() function to create references, similar to Id in View System.
val (image, text) = createRefs()Inside ConstaintLayoutExample function, put a ConstraintLayout Composable and create two references we will need, for the image and text.
Image (
...
modifier = Modifier.constrainAs(image) {
...
}
)
Text (
...
modifier = Modifier.constrainAs(text) {
...
}
)
MainActivity.kt: