ConstraintLayout in Android using Jetpack Compose
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.
Step by Step Implementation
Step 1: Create a New Project (Or use it in the existing Compose project)
To create a new project in the Android Studio Canary version, refer to the article How to Create a new Project in the Android Studio Canary Version with Jetpack Compose.
Step 2: Adding Dependencies
Open build.gradle(app) and add the following dependency.
Step 3: Working with the Composable
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. Inside ConstaintLayoutExample function, put a ConstraintLayout Composable and create three references we will need, for the top bar, logo, and bottom text.
Then Create a topbar inside ConstraintLayout, refer to the comment below in code for a better understanding of how to put constraints.
Similarly, Create the Image and Text Composable and constraints.
And we are done, now call the composable from setContent in MainActivity Class
Run the app and see how Composables are constrained according to the code. Below is the complete code for the MainActivity.kt file.
If having any issue, refer to the Github Project.