Writing in the front

ConstraintLayout is the Star of Future Layout. Looking back, I feel that this article focuses too much on visual operation. I looked at ConstraintLayout’s official documentation and decided to look at ConstraintLayout at the code level from an official documentation point of view.

Inheritance relationships





Inheritance relationships

ConstraintLayout, like any other layout, inherits from the ViewGroup, but it is more flexible and powerful in adjusting the position and size of controls.

Versioning support

ConstraintLayout is a Support library, meaning forward compatibility. It is compatible with API 9, or Android 2.3, and is generally 2.3 or higher, so developers don’t have to think about versioning unless it is unusual. The following is the official document citation:

Note: ConstraintLayout is available as a support library that you can use on Android systems starting with API level 9 (Gingerbread).

New features

ConstraintLayout offers some new features over traditional layouts in the following areas:

  • Relative positioning
  • From the outside
  • Center and inclination
  • Performance of visibility
  • The size constraint
  • Chain
  • Auxiliary tool

Let’s take a closer look at these new features.

Relative positioning

ConstraintLayout Relative positioning is the basic building block of ConstraintLayout, which means that one control is positioned relative to another. You can add horizontal and vertical constraints.

  • Horizontal: Left, Right, Start, End
  • Vertical: Top, Bottom, Baseline (the Baseline at the Bottom of the text) usually adds constraints from one edge to the other, just as button B is positioned to the right of button A below:




Fig. 1 – Example of relative positioning

The code implementation for this case looks like this:

<Button android:id="@+id/buttonA". /> <Button android:id="@+id/buttonB". app:layout_constraintLeft_toRightOf="@+id/buttonA" />Copy the code

The system then knows that the left side of button B is constrained to the right side of button A, where the constraint can be understood as edge alignment.





Fig. 2 – Constraints on relative positioning

In the figure above, each edge (top, bottom, baseline, left, Start, right, end) can form constraints with other controls. The relative positioning relationships formed by these edges are listed as follows:

* layout_constraintLeft_toLeftOf          // Align the left left
* layout_constraintLeft_toRightOf         // Align left to right
* layout_constraintRight_toLeftOf         // Align the right left
* layout_constraintRight_toRightOf        // Align the right to the right
* layout_constraintTop_toTopOf            // Align top and top
* layout_constraintTop_toBottomOf         // Align top and bottom
* layout_constraintBottom_toTopOf         // Align bottom top
* layout_constraintBottom_toBottomOf      // Align bottom bottom
* layout_constraintBaseline_toBaselineOf  // Text content baseline alignment
* layout_constraintStart_toEndOf          // Start edge aligned to tail
* layout_constraintStart_toStartOf        // Align the start edge to the start edge
* layout_constraintEnd_toStartOf          // Align the tail to the starting edge
* layout_constraintEnd_toEndOf            // Align tail to tailCopy the code

These attributes need to be constrained by ids that point to the control or to the parent container (ConstraintLayout), such as:

<Button android:id="@+id/buttonB". app:layout_constraintLeft_toLeftOf="parent" />Copy the code

From the outside





Fig.3 – Relative positioning margins

I’m sure you understand the margins here, so I don’t need to repeat them here. The attributes of the margins are listed as follows:

* android:layout_marginStart
* android:layout_marginEnd
* android:layout_marginLeft
* android:layout_marginTop
* android:layout_marginRight
* android:layout_marginBottomCopy the code

Take Figure 3 as an example, where GONE MARGIN refers to that after B adds A constraint to A, if A’s visibility becomes GONE, then B’s MARGIN can be changed, that is, B’s MARGIN can be divided into two states according to A’s visibility.

* layout_goneMarginStart
* layout_goneMarginEnd
* layout_goneMarginLeft
* layout_goneMarginTop
* layout_goneMarginRight
* layout_goneMarginBottomCopy the code

Center and inclination

In the middle

In the relative Positioning section, we learned about adding constraints between two controls. Now let’s look at establishing constraints between a control and its parent layout. When you add constraints to ConstraintLayout to both sides of the control in the same direction (landscape or landscape), it looks like figure 4.





Fig.4 – Center positioning

The code is written like this:

<android.support.constraint.ConstraintLayout ... > <Button android:id="@+id/button".app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent/>
<android.support.constraint.ConstraintLayout/>Copy the code

This situation feels as if there are two opposite and equal forces pulling on the control, which is why the control is centered.

Note: If the control is the same size as ConstraintLayout in a centered direction (landscape or vertical), then there is no center, and the constraint is meaningless.

Tendency to

In cases where the constraint is in the same direction and opposite, the default control is middle, but it can also be like a tug of war, where the two constraints are not equal in force, resulting in a tendency, which has properties like:

* layout_constraintHorizontal_bias
* layout_constraintVertical_biasCopy the code




Fig. 5 – Center with inclination

The following code makes the left side 30% and the right 70% (default 50% on each side), so that the left side is shorter, as shown in Figure 5. The code looks like this:

<android.support.constraint.ConstraintLayout ... > <Button android:id="@+id/button".app:layout_constraintHorizontal_bias="0.3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent/>
<android.support.constraint.ConstraintLayout/>Copy the code

Screen adaptation can be easily achieved by setting preferences.

Performance of visibility

ConstraintLayout has special treatment for controls whose visibility is marked view.gone (hereafter “GONE control”). In general, GONG controls are not visible and are no longer part of the layout, but ConstraintLayout has an important difference from traditional layout calculations:

  • In the traditional layout,GONEThe size of the control will be considered 0 (aspointTo deal with)
  • In ConstraintLayout,GONEThe control’s size is still the same as when it was visible, but its margin size is 0




Fig. 6 – Performance when visible

This particular behavior allows us to tag without disrupting the layoutGONEControl is useful for simple layout animations.

Explain: the author in the understanding of the original sentence is not very understanding, hope that experienced readers can point out the maze, the original text is as follows:

This specific behavior allows to build layouts where you can temporarily mark widgets as being GONE, without breaking the layout (Fig. 6), which can be particularly useful when doing simple layout animations.

See the GONE MARGIN property in the MARGIN section above for the MARGIN change Settings for the constrained control (B) when the target control (A in Figure 6) is set to GONE.

Note:The margin used will be the margin that B had defined when connecting to A (see Fig. 6 for an example). In some cases, this might not be the margin you want (e.g. A had a 100dp margin to the side of its container, B only a 16dp to A, marking A as gone, B will have a margin of 16dp to the container). For this reason, you can specify an alternate margin value to be used when the connection is to a widget being marked as gone (seethe section above about the gone margin attributes).

The size constraint

ConstraintLayout itself can define its own minimum size:

  • Android :minWidth Sets the minimum width of the layout
  • Android :minHeight Sets the minimum height of the layout

These minimum sizes are valid when ConstraintLayout is set to WRAP_CONTENT.

Control size constraints Control size can be set with android:layout_width and Android :layout_height in three ways:

  • Use fixed values
  • Using WRAP_CONTENT
  • Use 0DP (equivalent to MATCH_CONSTRAINT)




Fig. 7 – Size constraints

The first two are used in the same way as the other layouts, and the last is to resize the control through a fill constraint (figure 7, (a) wrAP_content, (b) 0DP). Code examples are as follows:

<Button android:layout_width="0dp" // Set MATCH_CONSTRAINT on the width, combining lines 3 and 4 to implement the constraint
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>Copy the code

If the control has a margin, the margin is taken into account in the sizing calculation, as shown in Figure 7 (c).

Type on the blackboard, underline: Generally MATCH_PARENT is not supported with ConstraintLayout, but it is supported with simple layout structures, such as controls whose constraints are associated only with ConstraintLayout. Its role is the same as MATCH_CONSTRAINT.

Ratio The ratio here refers to the aspect ratio, by setting the ratio so that one of the dimensions varies with the other. To achieve scaling, you need to constrain the width or height of the control and set the size to 0DP (or MATCH_CONSTRAINT), as follows:

<Button android:layout_width="wrap_content"
    android:layout_height="0dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintDimensionRatio="1" />Copy the code

In the code above, the height of the button is constrained and set to 0dp, so its size is scaled to the width.

There are two formats for setting the scale:

  • Width and heightthan, can be understood asSize of constrained party: size of other party
  • Constrained one party size/another party sizeTo get theFloating point Numbersvalue

If the width and height are MATCH_CONSTRAINT (0DP) and constraints are set, then you need to add W, or H, before the scale to determine whether the constrained side is high or wide, and then the constrained side calculates its size proportionally from the unconstrained side.

Regarding the above paragraph, the original text reads:

You can also use ratio if both dimensions are set to MATCH_CONSTRAINT (0dp). In this case the system sets the largest dimensions the satisfies all constraints and maintains the aspect ratio specified. To constrain one specific side based on the dimensions of another. You can pre append W,” or H, to constrain the width or height respectively.

Personally, I feel that the official documents are vague about this section, which may be related to my English reading ability. I hope the experienced people can answer my questions and clarify my doubts.

For the above case, the code is as follows:

<Button android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintDimensionRatio="H,16:9"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>Copy the code

The above code constrains both the width and the height. Pass H to specify that the height is constrained, so the size of the height will be proportional to the size of the width, as shown in the figure below:





Ratio

As for why the height fills the screen but not the width, the mystery lies in the following sentence. To understand it, you understand the essence of proportional use:

In this case the system sets the largest dimensions the satisfies all constraints and maintains the aspect ratio specified.

Chain

A Chain is a series of bidirectional controls connected together (as shown in Figure 8, a Chain is the smallest unit with only two components).





Fig. 8 – Chain

Chain header Horizontally, the Chain header is the left-most control of the Chain. Vertically, the Chain header is the topmost control of the Chain.

Chain margin If a margin is defined during connection, the Chain changes. In the SPREAD CHAIN, margins are removed from the allocated space. The original text reads as follows:

If margins are specified on connections, they will be taken in account. In the case of spread chains, margins will be deducted from the allocated space.

When the layout_constraintHorizontal_chainStyle or layout_constraintVertical_chainStyle attribute is set to the first element of the Chain, The Chain changes according to a specific style (the default style is CHAIN_SPREAD). The style type is as follows:

  • CHAIN_SPREADElements are scattered (default style)
  • inCHAIN_SPREADMode if some controls are set toMATCH_CONSTRAINT, the control will divide all remaining space evenly and “eat”
  • CHAIN_SPREAD_INSIDEThe elements on either side of the Chain are attached to the parent container, and the other elements are adopted in the remaining spaceCHAIN_SPREADmodel
  • CHAIN_PACKEDAll controls in the Chain are merged and centered in the remaining space




Fig.10-chain style

Weighted Chain Default chains are evenly distributed in space. If one or more of the elements use the MATCH_CONSTRAINT attribute, they fill out the remaining space evenly. The attributes layout_constraintHorizontal_height and layout_constraintVertical_weight control how elements using MATCH_CONSTRAINT divide space equally. For example, if a Chain contains two elements using MATCH_CONSTRAINT, and the first element uses a weight of 2 and the second element uses a weight of 1, the space taken up by the first element is twice as much as the second element.

  • Auxiliary tool

For ConstraintLayout, the Helper is Guidline. To learn more about Guideline, try the Guideline operation in Future Layout Star – ConstraintLayout. On this basis, visit the Guideline class for details, and the code examples of Guideline class are attached for readers to know:

<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">

    <android.support.constraint.Guideline
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/guideline"
            app:layout_constraintGuide_begin="100dp"
            android:orientation="vertical"/>

    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            app:layout_constraintLeft_toLeftOf="@+id/guideline"
            android:layout_marginTop="16dp"
            app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>Copy the code

Relevant methods

Public constructor
ConstraintLayout(Contextcontext)
ConstraintLayout(Contextcontext,AttributeSetattrs)
ConstraintLayout(Contextcontext,AttributeSetattrs, int defStyleAttr)
Public methods
void addView(Viewchild, int index,ViewGroup.LayoutParamsparams)
ConstraintLayout.LayoutParams generateLayoutParams(AttributeSetattrs)
int getMaxHeight(a)
int getMaxWidth(a)
int getMinHeight(a)
int getMinWidth(a)
void onViewAdded(Viewview)
void onViewRemoved(Viewview)
void removeView(Viewview)
void requestLayout(a)
void setConstraintSet(ConstraintSetset)
void setMaxHeight(int value)
void setMaxWidth(int value)
void setMinHeight(int value)
void setMinWidth(int value)
Protected methods
boolean checkLayoutParams(ViewGroup.LayoutParamsp)
ConstraintLayout.LayoutParams generateDefaultLayoutParams(a)
ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParamsp)
void onLayout(boolean changed, int left, int top, int right, int bottom)
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Write in the last

The first time I tried to translate an official document with my last remaining English ability, and now I feel dizzy and confused as I read the dense English written here. If you find any mistakes in this article, please feel free to leave a comment below. ConstraintLayout, in my opinion, requires more use, practice, and source code analysis. I hope this article will help readers get started with ConstraintLayout. Translation is not easy, please indicate the link for reprinting, and finally attach the address of the official document for readers to compare and study, thank you for reading! Developer. The android. Google. Cn/reference/a…