Android ConstraintLayout Example Tutorial

In this tutorial, we are going to learn how to use new android ConstraintLayout. Few days ago, I opened by Android Studio, there was a notification for android studio 2.2 stable version so I decided to update my android studio.

I have been hearing about the new android layout – ConstraintLayout – but I did not have time to check it but now that I have android studio 2.2 which is the lowest version that supports ConstraintLayout, I decided to give it a try.

 

So what is android new ConstraintLayout

According to android developers user guide,  ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It’s similar to RelativeLayout in that all views are layed out according to relationships between sibling views and the parent layout, but it’s more flexible than RelativeLayout and easier to use with Android Studio’s Layout Editor.

The fun thing about building android UI with ConstraintLayout is that everything you need to use is available in android studio. It involves simple drag and drop View widgets from the Palette to the designer editor.

Before we go deeper into android ConstraintLayout, we are going to see who the interface appear in android studio.

Please note that you have to set up android ConstraintLayout in your android project if you are planning to use it. Android ConstraintLayout goes as a support library and it is backward compatible to android version 9.

 

ConstraintLayout Requirements

1. Android Studio version 2.2 and above

2. Android min sdk 2.3

 

Setting Up ConstraintLayout in Android Project

To set-up android ConstraintLayout in the your android project, we will first check if the ConstraintLayout tool has been installed in Android Studio. In other to achieve this, open your android studio IDE and click on

1. SDK Manager menu icon

2. Android Studio Default Setting pop-up window will appear

3. Select the SDK Tool menu

4. Go to Support Repository and check ConstraintLayout for Android and Solver for ConstraintLayout

5. Click the OK button to install

That is it and we are done installing ConstraintLayout for android and Solver for ConstraintLayout as shown below.

Android ConstraintLayout

 

CREATE NEW ANDROID PROJECT

Lets start to soil our hands with android ConstraintLayout. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidConstraintLayout

Package: com.inducesmile.androidconstraintLayout

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Update Build.Gradle

Before we can use ConstraintLayout features in our android project, we will add the library to our build.gradle app module dependencies section.

Open your build.gradle (Module app) and add the code below.

applicationId "com.inducesmile.androidconstrianlayout"
apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidconstrianlayout"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
}

Once the library is add, the light yellow sync now bar will appear. Click on sync now link and after some few minutes the library will be available in your android project.

Now, we are going to see the difference between android studio 2.2 with support for ConstraintLayout and android studio versions below 2.2

Android Studio Design Editor with ConstraintLayout

Android ConstraintLayout

As you have seen on the image above, there are different sections in Android Studio Layout Editor as highlighted with yellow foreground color. Take some time and familiarize yourself with the menu options.

Now that we can use Constraintlayout in our android project, it is time to see how we can use it. There are different options available but we will start with converting an already existing layout file to a Constraintlayout.

 

Convert a layout to Constraintlayout

Although you are free to use non-Constraintlayout files in your project but if you find yourself in situation where you would like to convert a layout to a Constraintlayout, then the following procedures will get you there.

Open your existing layout in Android Studio and click the Design tab at the bottom of the editor window.

In the Component Tree window, right-click the layout and then click Convert layout to ConstraintLayout

android constraintlayout convert

 

Create a new Constraintlayout

To create a new Constraintlayout in your android project, follow the steps below.

1. Click anywhere in the Project window and then select File > New > XML > Layout XML.

2. Enter a name for the layout file and enter “android.support.constraint.ConstraintLayout” for the Root Tag.

3. Click Finish

You can as well see the diagram that illustrate it below.

layout4 layout5

 

Add Views to Constraintlayout

We have been busy trying to setup and understand how android studio manages constraintlayout. now, we will move our attentions to adding view widgets to constraintlayout.

I will like to emphasize that there are few rules that govern adding constraint to Views. This is a snippet from android developers guide.

 

When creating constraints, remember the following rules:

1. Every view must have at least two constraints: one horizontal and one vertical.

2. You can create constraints only between a constraint handle and an anchor point that share the same plane. So a vertical plane (the left and right sides) of a view can be constrained only to another vertical plane; and baselines can constrain only to other baselines.

3. Each constraint handle can be used for just one constraint, but you can create multiple constraints (from different views) to the same anchor point.

When you add a constraint to a view, you will see in the property section, the view attributes. You can edit your view properties in XML code but it is preferable to use the property window. There is a link below – view all properties. If the view property you want to edit is not visible then click on the link to see all the properties.

 

Delete a View Constraint

 

Deleting a single constraint in a View

In other to delete a constraint, hold your cursor on constraint handle, when the color turns red, click to delete it.

delete_constraint

 

Deleting all constraints in a View

There is a simple way to delete all the constraint in a view. To delete it, simple select the view in particular and a rectangle icon will appear. Click on the icon to delete all the constraints in the view.

delete single constriants in android

 

Deleting all constraints in a layout

In the design view layout editor, there is a little icon with X inscription on top. When you hover on the icon a tool tip text will appear (Clear all constraints). Click on this icon to clear all the constraints in the layout.

clear all constraints in android

 

Resize a View Constraint

Resizing a View involves increasing and decreasing the side of the View. This can be achieve by dragging in and out the constraint resize handler. As you resize a view, its new constraints are updated automatically.

resize constraint in android

 

Adding Opposing Constraints on a View

When an opposing constraints are added to a view, the opposing lines appears squiggly like a spring. This is an indication that two opposite forces are acting on the view. Before effect can be different depending on what the view size is set (Fixed, Wrap content, Any size).

If the view size is set to any size, you can employ the horizontal or vertical constraint bias to move the view. We will also use this opportunity to look into how we can edit the view layout width and height using the property inspector Pane.

android constraint_property

The square image that represents the view dimension gives a fine control over how you can edit or constraint views in a layout. The inner four bars can represent different layout width and height as shown below.

dimension_constraints

Android dimension constraint This image represents the Fixed Mode. With the Fixed mode you will have the option to specify a View layout width and height

dimension3 This represents the Wrap_content. In the wrap content mode, the view will assume the width and height of it’s content.

dimension2 This represents the Any size. This is equivalent to match_parent. In this case, the View will take up all the available space assigned by the constraint.

 

Constraining a View to it’s parent

As said before, there are many ways a View widget can be connected or positioned in a layout. In this section, we will look at one of the options which is constraining an ImageView to its parent layout.

Drag and drop an ImageView widget from the Palette panel to the layout. Click and drag the side constraint handle of the View to the edge of its parent as shown.

parent_layout_constraint

 

Adding Constraints between Views

It is possible to add a constraints between Views. To achieve this, simply drag from the constraint handle of one View to the other edge of the View. According to the rules guiding constraints, horizontal constraints from a view should be added to the horizontal edge of another View. Don’t try to use constraints from horizontal side to vertical size.

view_to_view_constraint

 

Adding Baseline Alignment Constraint

You can create an align text baseline between two different View widgets. This can come handy when you want to align two different view with their text baselines

It is very easy to create a baseline constraint. Hover your mouse on the baseline handle of some time and when the handle blinks white then click and drag the line to another baseline.

baseline_constraint

 

Adding Alignment Constraint

During UI design, there are situations when we need to align Views to match their edges. Some other times, we might want to give so margin so that one View will appear indented. We can achieve this based on adding alignment constraints. Look at the examples below.

Horizontal alignment constraint

alignment_contraints_one

Offset horizontal alignment constraint

alignment_constraint_two

 

Adding Constrain to a Guideline

Guideline is an invisible vertical or horizontal dash-line that can be added to layout. Once it is added in a layout, it is possible to add a constraint to it. The good thing about guideline is that the users of the app will not get to see then or feel like they exist.

You can use the circle in the guideline to help you position it where it will create more impact. It uses a percentage value to let you know its vertical position on the layout.

In other to add a guideline, click on icon in design view of the layout editor. The image below will let you know where you can find it.

guideline

From the drop-down menu, select either vertical or horizontal guideline and it will be added in your layout. Feel free to move it and position it where you will like to place it. A simple constraint example using a vertical guideline is shown below.

guideline_constraint

 

Using Auto-connect and Infer Constraint

By default the Autoconnect is disable but when you enable Autoconnect, then it will automatically add constraints to view based on the position of the view and other Views around it.

Although, Autoconnect can make developing UI easier and faster but there are some few problems associated with Autoconnect.

There are times that Autocnnect constraints are not what you are looking for then you have to edit, add or delete the constraints to arrive on what you are looking to achieve.

If you are starting up with constraintlayout, I will suggest you disable the Autoconnect and focus on manual. This is help you understand how things work and remove on necessary issues you can’t explain if you jump into Autoconnect.

Another important feature is the Infer constraints. This will come handy when you want to create an overall constraints to all the views in a layout. Once you click on Infer constraint menu icon, it will scan all the views in the layout and add constraints with respect to their positions.

 

Conclusion

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

OTHER INTERESTING POSTS:

Add a Comment