The original article is from the gold-digging Reed APP team, reprinted to my trumpet again ~
Translated By Leelion6. There have been many articles about ConstraintLayout, but this article is very interesting to write and I feel the different writing thinking in different cultural environments. Most importantly, the content of this article is very detailed and beginner friendly, so it is translated for developers who need to learn. If you need more advanced usage, please go to see guo Lin and other gods more in-depth related articles.
In this tutorial, you will learn the basics of creating Android views by building a login interface from scratch using ConstraintLayout.
By Fuad Kamal
The original link: www.raywenderlich.com/9193-constr…
The required materials and source code download: koenig-media.raywenderlich.com/uploads/201…
A good Android app requires not only a nice UI, but also good performance. When drawing a page, you need to control where and how the view appears on the user’s screen.
Android offers a variety of layout types, all of which have different ways of identifying sub-views. All layouts come from the ViewGroup class. Common layouts for building Android UIs are FrameLayout, LinearLayout, and RelativeLayout.
These layouts are easy to use, but each has its limitations and some performance issues when the view structure becomes complex:
FrameLayout
The child View can only be positioned by setting the Gravity property relative to the parent ViewLinearLayout
Views are not allowed to overlap. In most cases, you have to use more than oneLinearLayout
In a nestedRelativeLayout
More performance is required because it always makes two layout measurements
ConstraintLayout already exists as a default layout in newer versions of Android Studio, and provides a number of ways to place objects: You can constrain them relative to their containers themselves, relative to other objects or to each other, and relative to guileline(helper lines) that you create yourself. These methods allow you to create large, complex, dynamic and responsive views at the same level, and even support animation!
Raze Galactic – An interstellar travel app
You can use the app to book trips between planets, plan a weekend getaway to the space station, and book a lunar rover when you arrive.
In this tutorial, you’ll learn the basics of ConstraintLayout by building the star Trek application’s login UI from scratch.
In the process, you will learn:
- How do I add and remove constraints
- How do I dynamically position UI elements relative to other elements on the interface
Note: This tutorial assumes that you are familiar with the basics of Android and Android Studio. If you’re not familiar with Android development, check out our getting Started Android tutorial series.
An introduction to
Open Android Studio 3.2.1 or later and create a new Android Studio project by selecting Start a New Android Studio Project from the startup screen.
On the next screen, enter Raze Galactic as Application name.
For Company domain, you can type in anything you like. This example uses raywenderlich.com.
For Project Location, select the address on your computer that is meaningful to you and make sure there are no Spaces in the address path. You can click on the ellipsis to the right of the project location field… To directly select the directory on the computer.
Finally, make sure Include Kotlin Support is selected (add Kotlin language support) and click the Next button.
Translator’s note: It is not necessary to check Kotlin language support in this article, the subsequent content does not use Kotilin directly, so if you are a pure JAVA language developer or do not want to use Kotlin, it is perfectly OK to leave it unchecked.
On the Next screen, to select Android devices, you need to select Phone and Tablet, then SELECT API 28: Android 9.0 (Pie) and click Next.
Note: the API section can be selected as you like, not necessarily as high as Android9.0.
On the “Add an Activity to Mobile” screen, select Empty Activity. Later you will add UI elements to this empty activity to understand layout operations in Android.
Next — you guessed it — click Next!
On the last wizard page, Configure Activity keeps all the default configurations and presses Finish to complete the project configuration.
Check the ConstraintLayout version
Before you start creating a new layout, you need to check ConstraintLayout for a version update.
You can find this information in the build Gradle file of the app module. In Andoird Studio, open app ▸ build.gradle and check it for dependencies {… }.
Among various kinds of building dependencies, you should be able to find the implementation ‘com. Android. Support. The constraint: the constraint – layout: x’, where x is ConstraintLayout the version used in the project.
To complete this tutorial, you need ConstraintLayout 1.1.3 or later. To ensure that you have the latest version of ConstraintLayout library, select Tools ▸ SDK Manager from the menu.
ConstraintLayout for Android click the SDK Tools TAB and view ConstraintLayout for Android under Support Repository. If installed is displayed, you are using the latest version
Next, check the box called Show Package Details to see the version of the libraries included in the project. The version number in the Gradle file needs to match the version installed in the SDK Manager.
Configure Android Studio’s design interface for efficient constrained layout development
Before continuing with this tutorial, set up the Android Studio view display to make it easier to add and view constraints and their associated elements.
Start by opening activity_main.xml, then click the Select Design Surface icon in the toolbar and Select Design + Blueprint.
You can now see the blueprint screen next to the Design Preview screen at work.
The blueprint view helps you see the constraints and guidelines more clearly, without being distracted by the content or context.
When developing your APP UI, you can switch back and forth between the code view (Text TAB) and the Design TAB.
Code views allow you to view and edit the XML behind the layout, and design views are useful for visually manipulating UI elements. The design view also provides a Component Tree, which allows you to view and select all the UI elements present in the program.
When you’re in code view, it’s useful to be able to see visual previews and blueprints. This way, when you select any element in the preview screen, the corresponding code block in the XML becomes highlighted.
If you do not see the Preview screen in the code view, click the Preview TAB on the right.
Create a new ConstraintLayout from scratch
For the next step, open activity_main.xml and switch to code view to see the source code for the file:
<? The XML version = "1.0" encoding = "utf-8"? > <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>Copy the code
Please note that the layout of the default root element is the android support. The constraint. ConstraintLayout. In addition, with “Hello World! The TextView element of the text already has constraint attributes, such as app:layout_constraintBottom_toBottomOf=”parent”, which binds the bottom of the view to the bottom of its parent container.
After constraining the top, bottom, left, and right of its parent container, contain “Hello World!” The TextView is in the center of the screen.
Switch to Design view and move the mouse cursor over the “Hello World! On the TextView, you can see four wavy lines connecting the TextView to its parent container. These lines indicate that the constraint rules have been applied to the TextView.
If the lines do not appear, click on TextView and they will appear. If the Show Constraints view option is selected, you can see all Constraints without using the mouse cursor to hover over or select any view.
Add images to your APP
For the next step, you’ll need the rocket image you saw in the screenshot of the application at the beginning of this tutorial. Use the “Download Materials” button at the beginning of the tutorial to download the materials for this tutorial, or click here to download. You can find track_icon.png in the RazeGalactic-starter folder.
Get track_icon.png and add it to your project’s Drawable folder. You can do this by using Command-c on a Mac or Control-c on Windows, Then right-click on the Drawable folder in your Android project and paste the image into your project using Command -v on Mac or Control-v on Windows.
You can drag and drop UI elements from the Palette into the design interface. If you do not see Palette, click the vertical Palette TAB icon.
Delete the “Hello World! , and drag the following UI elements to the view in the Palette:
-
An ImageView prompts you to select the rocket image when selecting an image.
-
Three Button
-
Three TextView
Change the text of UI elements and drag them around the screen to make them look like the final layout preview at the beginning of this tutorial. Don’t worry too much about your view’s size, spacing, or alignment accuracy.
Next, you need to add the android: textAppearance = “@ style/textAppearance. AppCompat. Headline” to the razr Galactic TextView in order to obtain the appropriate style.
Note that these little lines are helpful as you drag views across the screen. They can easily align views with each other.
Test the position of the view
Now, build and run your application.
Day lulu! The views are not aligned as you assigned them in the design view! Everything is curled up in the top left corner of the screen. What’s going on?
HMM.. Well, Android gets this part of the information on how to place UI elements, because the view you’re adding doesn’t have any defined constraints. So you need to fix that.
Back in Android Studio, you can see that each new view in the Component Tree now has a set of errors. To see the full text of the error, click the red exclamation mark in the Component Tree.
The error is as follows:
This view is not constrained. It is only included in the position at which it was added, so it will be placed at (0,0) at run time unless you add the constraint. Switch back to the code view to examine the source code for the layout XML. Note that the source code for any view has some attributes prefixed with Tools, such as:
<ImageView
android:id="@+id/imageView"
android:layout_width="46dp"
android:layout_height="46dp"
app:srcCompat="@drawable/track_icon"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="16dp" />
Copy the code
The layout editor allows you to place widgets anywhere on the canvas and record the current location using the Tools prefix property. Keep in mind that these properties are not applied at actual runtime.
The attributes of the Tools prefix serve in the layout editor and are only useful in the preview view of the XML, not in the actual run time.
Get to know the layout editing toolbar
Switch back to the layout design view and you can see a bunch of widgets at the top of the layout preview. If you hover over each control, you can read a brief description of that control.
Automatic connection
Click the magnet icon in the toolbar to enable Autoconnect, drag any view to the area near the corner of the superview, and Android Studio will automatically create the new constraint for you.
Note that this only applies to creating constraints between UI elements and their superviews, not between UI elements, so Autoconnect is of very limited use. In most cases, you should turn Autoconnect off.
Auto join (speculative constraint)
Next, click the Infer Constraints button and Android Studio will automatically add the Constraints that are missing from the layout.
Build and run your application again, and now the components are not in the corner, but where you left them.
This is the easiest way to add constraints, but it can also be the worst. Because the intent of the Android Studio layout is often different from your actual intent.
The layout may be fine for a certain size using autoconnect, but it may not look as you would like for different screen sizes or screen orientations.
Clear all constraints
If the constraints are messy, you can remove all the constraints and re-add them from scratch. To do this, click the Clear All Constraints button to Clear All Constraints on the current page.
Add and remove individual constraints
Android offers a variety of options to restrict UI elements to different parts of the screen, giving you flexibility to design your layout.
In this part of the tutorial, you will learn how to bind objects to their containers, remove individual constraints, and bind objects to another object to achieve dynamic layout.
Binds an object to its container
Notice that when you click on ImageView, it is highlighted and small circles appear at the top, bottom, left, and right of the view. These circles are your constraint anchors.
When you hover over one of the constraint anchors, it will flash green. Android Studio will prompt you to create constrained connections.
Click the circle to the left of the element and drag it to the left. As you drag, lines with arrows appear, creating constraints between the left side of the UI element and the element you want to connect it to.
Drag the circle to the left of the view and constrain the left side of the circle ImageView to the left side of the superview. Repeat this for the top of the circle ImageView, constraining it to the top of the superview. You have now limited the ImageView constraint to the upper-left corner of the view.
Drag the image down a bit and Android Studio will create a margin at the top. Set the top margin to 30DP by editing the XML code in the code view or editing it in the Attributes inspector of the Design view.
Next, select the Raze Galactic TextView and drag the left constraint anchor point to the left and the right constraint anchor point to the right of the superview. By restricting this UI element to the left and right, Android understands that you want it to be centered.
Delete individual constraints
Next, place the mouse cursor over one of the constraint anchors where the constraint is set, and the circle representing the arrow should now flash red, and the constraint is highlighted in red.
Clicking the anchor removes the constraint. Do not click for now and leave the constraint anchor in place, but remember this if you need to remove the constraint later.
Now that you know how to constrain UI elements to their parent container borders, it’s time to learn how to constrain UI elements to each other.
Constrain objects to each other
In this step of the tutorial, you will implement the Raze Galactic TextView to always align with the rocket image.
To do this, you need to bind the top Raze Galactic TextView anchor to the top ImageView anchor and attach the bottom TextView anchor to the bottom ImageView anchor. The two views are aligned vertically.
Now, if you hold and drag the rocket up and down, you will see the Raze Galactic move up and down with the image.
Later, you will see how to create such an alignment using the Alignment menu. However, the method isn’t always perfect, so it’s also a good thing to know how to do it manually.
Switch to the code view in Android Studio and examine the code for the view where you just added the constraint:
<ImageView
android:id="@+id/imageView2"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_marginStart="16dp"
android:layout_marginTop="30dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/track_icon"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Raze Galactic"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"
app:layout_constraintBottom_toBottomOf="@+id/imageView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/imageView2"/>
Copy the code
Now that you’ve added some constraints, the Attributes prefixed with Tools are gone, because Android Studio no longer requires these design-time attributes.
Each constraint you add is withdrawn in the code, such as app:layout_constraintTop_toTopOf=”parent”, representing the top constraint of the element at the top of the parent layout.
You can see that Android Studio has set some margins for you that you probably didn’t want to add. These margins might look like Android :layout_marginStart=”16dp”.
Go ahead and switch back to the Design view after removing the margin property in the Raze Galactic TextView. Now you will see that the Raze Galactic TextView should be aligned with the rocket image.
There are no more errors with these two views, because Android Studio has already met the minimum amount of information needed to place these UI elements.
Note: You may still see warnings about using hard-coded strings or missing contentDescription. But you can ignore that for now.
Now you should align the ** Login** button with the Sign Up button, just like you align the Raze Galactic TextView with the rocket image. To do this, you will need to set three constraints:
The top anchor of the Login button is located at the top of the Register button. The bottom anchor of the Login button is located at the bottom of the Register button. The left anchor point of the “Login” button is to the right of the “Register” button, and set a starting margin of 30DP from the left to leave some space between them.
Apply alignment constraints
Select the Raze Galactic TextView and click the anchor on the right to remove these constraints. Then, while TextView is still selected, click the Align tool in the toolbar, and select Horizontally in Parent.
This automatically centers the Raze Galactic TextView relative to the parent container. This is the same effect you achieved earlier when you manually added the constraints.
In fact, if you switch to the code view and carefully examine the Raze Galactic TextView, you’ll notice that Android Studio has added the following constraint properties:
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
Copy the code
What, you might ask, is layout_constraintHorizontal_bias that is automatically added to Android Studio?
Constraint Bias
When a view is constrained horizontally or vertically, whether superview or otherwise, it has a constraint bias of 0.5 or 50% by default. In other words, the view remains centered between its constrained edges.
The constraint bias ranges from 0.0 (0%) to 1.0 (100%), with horizontal constraint bias increasing from left to right and vertical constraint bias increasing from top to bottom. Constraint bias is useful for dynamically positioning views for different screen sizes.
To more easily understand how constraint bias works, switch back to design view. Select the Raze Galactic TextView and view the View Inspector and various Attributes on the right.
The vertical slider on the left side of the view viewer controls vertical constraint bias, and the vertical slider on the bottom controls horizontal constraint bias. Drag each slider to see how constraint bias works:
Before proceeding, reset the deviation between the horizontal and vertical constraints to 50%.
Align the left edge and distribute vertically
Next, select all textViews, Google Sign-in, and sign-up buttons at the same time. You can hold down the Shift key and click on each UI element to select them all in turn. Then, from the toolbar, click Align and select the Left edge.
This is the layout after applying left alignment:
Do you notice anything wrong here? Horizontal constraints on the Raze Galactic TextView have been removed.
The left edge aligns the view with the leftmost view selected, and what it really does is create a left constraint dependency from a view in descending order, with the bottommost view acting as the anchor.
Therefore, for the Left edge (Left edge) command to work, it must remove the existing horizontal constraints for the remaining selected views.
To reverse the order of constraint dependencies, apply the Left edge command again. You can see that the constraint arrow now points up.
Now, using the same UI element that you selected in the previous step, click the Pack menu and select Distribute Vertically.
After vertical distribution, your screen should look like this:
Also, you may have noticed a similar problem: the constraint property connecting the bottom of the rocket icon to the Raze Galactic TextView has disappeared.
The constraint dependencies are arranged in descending order, just as they are after the first Left edge command. Unfortunately, there is no easy way to solve this problem, so you must manually create vertical distributed constraints.
This tutorial will cover how to do this in the next section, so please go ahead and undo the Distribute command.
Note: the Align and Pack commands may not work properly. They may remove existing constraints, and they may not move some constrained views. Be sure to check the constraints of the affected view before and after applying these commands.
Use the default margin
To create a vertically distributed constraint, simply join constraints with the same margin. One trick to do this quickly is to use the Default Margin tool.
Now click the Default Margin button and set the value to 60dp, then attach the top constraint of the Google Login button to the bottom of the Raze Galactic TextView. You will notice that the Google login button will automatically change position, leaving 60dp space between it and the Raze Galactic TextView. Magic:]
Create the remaining vertical constraints as shown in the GIF above. Finally, bind the left side of the Raze Galactic TextView to the right side of the rocket icon with a margin of 30dp.
Check the component tree to see if there are other errors. If there are no errors, congratulations!
Build and run your application, and now everything should be displayed in the emulator with the proper layout.
What’s next?
You can download the final version of this project using the Download Material button at the top of this tutorial.
ConstraintLayout Building a UI in a layout editor can be frustrating because some tools are not smart enough. However, if you know how to use them correctly, you can save a lot of time.
Other layout editor tools are not mentioned in this tutorial, but you can use them to see how they work. Take a look at the Documentation for Google ConstraintLayout to learn more.
For a more complex ConstraintLayout example, see our follow-up article ConstraintLayout Android Tutorial: Complex Layout.
For more examples of ConstraintLayout, check out our Android Apprentice book, which uses ConstraintLayout as the layout for all pages.
ConstraintLayout You now have the basics of ConstraintLayout, and for more advanced features and tips on how to handle complex layouts, stay tuned for our upcoming ConstraintLayout Android tutorial: Complex layout in which you will build a more complex constraint view for the Raze Galactic travel application and then animate it!
If you have any questions or comments, feel free to leave a comment below