当前位置:网站首页>Constraintlayout Development Guide
Constraintlayout Development Guide
2022-06-27 02:01:00 【ExtraLazy】
ConstraintLayout
ConstraintLayout It's a use “ Relative positioning ” A layout that flexibly determines the location and size of components , Solve the problem of too many nested page levels in development —— Too deep a level will increase the time required to draw the interface .
1、 Basic constraint
1.1 Relative positioning
Relative positioning is in ConstraintLayout One of the basic building blocks for creating layouts . These constraints allow you to position a given control relative to another control . You can constrain a control on the horizontal and vertical axes :
Horizontal axis : Left 、 Right 、 Start and end
Vertical axis : Top 、 Bottom and text baseline
The general concept is to constrain a given side of a control to the other side of any other control .
for example , To set the button B Navigate to the button A The right side of the ( chart 1):
<Button android:id="@+id/buttonA" ... />
<Button android:id="@+id/buttonB" ...
app:layout_constraintLeft_toRightOf="@+id/buttonA" />
This tells the system that we want the button B The left side of the is constrained to the button A The right side of the . Such a position constraint means that the system will try to share the same position on both sides .

chart 2 - Relative positioning constraints
This is a list of available constraints ( chart 2):
<!-- Where is my position? Where is my position -->
layout_constraintLeft_toLeftOf
layout_constraintLeft_toRightOf
layout_constraintRight_toLeftOf
layout_constraintRight_toRightOf
layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
<!-- American left and right -->
layout_constraintStart_toEndOf
layout_constraintStart_toStartOf
layout_constraintEnd_toStartOf
layout_constraintEnd_toEndOf
<!-- Copy baseline alignment -->
layout_constraintBaseline_toBaselineOf
They all quote id Another control , or parent( The parent container... Will be referenced , namely ConstraintLayout)
1.2 Margin

chart 3 - Relative positioning margin
If the side margin is set , They will be applied to the corresponding constraints ( If there is )( chart 3), Force the margin to the space between the destination and the source . The usual layout margin properties can be used for this effect :
android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
layout_marginBaseline
Please note that , Margins can only be positive or equal to zero , And take Dimension.
1.3 Connect to GONE Control's margins
When the visibility of the position constraint target is View.GONE when , You can also use the following attributes to indicate the different margin values to use :
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
layout_goneMarginBaseline
Visibility behavior
ConstraintLayout Mark as The control of View.GONE.
GONE As usual , Control does not display , Nor is it part of the layout itself ( namely , If it's marked , Their actual size does not change GONE).
But in terms of layout calculation ,GONE Control is still part of it , But there is an important difference :
- For layout channels , Their size will be considered zero ( Basically , They will be resolved to a point )
- If - They have restrictions on other controls , They will still be respected , But any margin will equal zero

This particular behavior allows you to build layouts , You can temporarily mark the control as is GONE, Without breaking the layout ( chart 7), This is especially useful when animating simple layouts .
Be careful : The margin used will be B Connecting to A Margin defined when ( See chart 7 Example ). In some cases , This may not be the margin you want ( for example ,A To one side of its container is 100dp The margin of ,B To A The margin of is only 16dp, take A Mark as disappeared ,B The margin to the container is 16dp). For this reason , You can specify an alternate margin value to use when connecting to a control that is marked as disappeared ( See the section above about the missing margin attribute ).
1.4 Center and offset (Centering positioning and bias)
A useful aspect ConstraintLayout It's how it handles “ impossible ” constraint . for example , If we have something similar :
<androidx.constraintlayout.widget.ConstraintLayout ...>
<Button android:id="@+id/button" ...
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</>
Unless ConstraintLayout And Of exactly the same size ,Button Otherwise, two constraints cannot be satisfied at the same time ( Both sides cannot be in the position we want ).
What happens in this case is , Constraints pull the control apart like opposing forces ( chart 4); The control will eventually be centered in the parent container . This also applies to vertical constraints .
The offset (bias)
The default setting when encountering this opposite constraint is to center the control ; But you can use the offset attribute to adjust the positioning to the other side :
layout_constraintHorizontal_bias
layout_constraintVertical_bias
for example ,
<androidx.constraintlayout.widget.ConstraintLayout ...>
<Button android:id="@+id/button" ...
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
for example , The following will make the left side have 30% The migration , Not the default 50%, This will make the left side shorter ,
More to the left ( chart 5):

similar :LinearLayout Weight distribution , It's a piece of cake to adapt to changes in screen size
1.5 Circular positioning (1.1 add )
You can constrain the center of one control relative to the center of another at an angle and distance . This allows you to position a control on a circle ( See chart 6). You can use the following properties :
layout_constraintCircle: Reference another control id
layout_constraintCircleRadius: Distance to the center of another control
layout_constraintCircleAngle: Control should be at which angle ( In degrees , from 0 To 360)


<Button android:id="@+id/buttonA" ... />
<Button android:id="@+id/buttonB" ...
app:layout_constraintCircle="@+id/buttonA"
app:layout_constraintCircleRadius="100dp"
app:layout_constraintCircleAngle="45" />
1.6 Dimensional constraints
Dimensional constraints
android:layout_width Can pass 3 There are different ways to set and android:layout_height attribute To specify the size of the control :
- Use specific dimensions ( Text value , for example 123dp or Dimension quote )
- Use WRAP_CONTENT, This will require the control to calculate its own size
- Use 0dp, amount to " MATCH_CONSTRAINT"

The first two work in a similar way to other layouts . The last one will resize the control in a way that matches the constraints set ( See chart 8,(a) yes wrap_content,(b) yes 0dp). If the margin is set , They will be taken into account in the calculation ( chart 8,(c) And 0dp).
Important note : MATCH_PARENT Not recommended for ConstraintLayout. Can pass MATCH_CONSTRAINT Place the corresponding left / Right or up / The lower constraint is set to define a similar behavior "parent".
ConstraintLayout Minimum dimension on the
You can define for yourself Minimum and maximum dimensions ConstraintLayout:
android:minWidthSet the minimum width of the layoutandroid:minHeightSet the minimum height of the layoutandroid:maxWidthSet the maximum width of the layoutandroid:maxHeightSet the maximum height of the layout
ConstraintLayout When its size is set to when , These minimum and maximum dimensions will be usedWRAP_CONTENT.
WRAP_CONTENT : Mandatory constraint ( stay 1.1 Add )
If the dimension is set to WRAP_CONTENT, It's in 1.1 In the previous version , They will be treated as literal dimensions —— in other words , Constraints do not limit the result dimension . Although usually this is enough ( And faster ), But in some cases , You may want to use WRAP_CONTENT, But continue to enforce constraints to limit the result dimension . under these circumstances , You can add one of the corresponding attributes :
- app:layout_constrainedWidth=“true|false”
- app:layout_constrainedHeight=“true|false”
MATCH_CONSTRAINT dimension ( Add in 1 . 1 in )
- layout_constraintWidth_min and layout_constraintHeight_min: The minimum size of this dimension will be set
- layout_constraintWidth_max and layout_constraintHeight_max: The maximum size of this dimension will be set
- layout_constraintWidth_percent and layout_constraintHeight_percent:
Set the size of this dimension as a percentage of the parent dimension
Min and Max
by min and max The indicated value can be Dp A dimension in , It can also be “wrap”, It will use the same value as performing the operation WRAP_CONTENT.
Percentage dimension
To use percentage , You need to set the following :
- The size should be set to MATCH_CONSTRAINT(0dp)
- The default value should be set to percentage app:layout_constraintWidth_default=“percent”
or app:layout_constraintHeight_default=“percent” - And then layout_constraintWidth_percent or layout_constraintHeight_percent Property is set to 0 To 1 Between the value of the
ratio
You can also define one dimension of a control as the ratio of another dimension . So , You need to set at least one constraint dimension to 0dp( namely MATCH_CONSTRAINT), And set the attribute layout_constraintDimensionRatio For a given ratio . for example :
<Button android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1" />
Set the height of the button to be the same as its width .
The ratio can be expressed as :
- A floating point value , The ratio between width and height
- “ Width : Height ” The ratio of form
If both dimensions are set to MATCH_CONSTRAINT(0dp), You can also use ratio . under these circumstances , The system sets the maximum size that satisfies all constraints and maintains the specified aspect ratio . To constrain a specific edge according to the size of the other side , You can pre attach W," or H, Constrain width or height, respectively . for example , If a dimension is constrained by two goals ( For example, the width is 0dp And focus on the parent ), You can indicate that... Should be restricted Which side , adopt In front of the ratio Add letters W( Used to limit the width ) or ( Used to limit the height ), Separate with commas :H
<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"/>
Will be in accordance with the 16:9 To set the height of the button , The width of the button will match the constraint of its parent .
chain
Chain on a single axis ( Horizontal or vertical ) Provide similar behavior on groups . The other axis can be constrained independently .
Create chain

Chain head
The chain consists of the first element set in the chain ( The chain “ head ”) Attribute control on :

The head is the leftmost control of the horizontal chain , The top most control of the vertical chain .
The margin in the chain
If margins are specified on the connection , They will be taken into account . In the case of a point difference chain , The deposit will be deducted from the allocated space .
The chain
When setting properties layout_constraintHorizontal_chainStyle or layout_constraintVertical_chainStyle On the first element of the chain , The behavior of the chain will change according to the specified style ( The default is CHAIN_SPREAD).
- CHAIN_SPREAD-- The element will be expanded ( Default style )
- Weight chain - stay CHAIN_SPREAD In mode , If some controls are set to MATCH_CONSTRAINT, They will divide the available space
- CHAIN_SPREAD_INSIDE-- similar , But the ends of the chain don't spread
- CHAIN_PACKED-- The elements of the chain will be packaged together . The horizontal or vertical deviation attribute of child elements will affect the positioning of packaged elements

Weight chain
The default behavior of the chain is to distribute the elements evenly in the available space . If one or more elements are in use MATCH_CONSTRAINT, They will use the available empty space ( They are equally distributed ). attribute layout_constraintHorizontal_weight and layout_constraintVertical_weight Will control how space is distributed between elements , Use MATCH_CONSTRAINT. for example , Use... On a chain containing two elements MATCH_CONSTRAINT, The weight of the first element is 2, The weight of the second element is 1, The first element will take up twice as much space as the second element .
Margins and chains ( stay 1 . 1 in )
When using margins on elements in a chain , Margins are additive .
for example , On the horizontal chain , If an element defines 10dp Right margin of , The next element defines 5dp The left margin of , So the result between these two elements is 15dp.
When the calculation chain is used to locate the remaining space of the project , The project and its margins will be considered together . The remaining space does not contain margins .
Virtual helper object
In addition to the internal functions detailed above , You can also use special helpers ConstraintLayout To help you with the layout . at present , The Guideline Object allows you to create relative to ConstraintLayout Horizontal and vertical guidelines for container positioning . You can then locate the control by constraining it to such a guide . stay 1.1 in ,Barrier also Group Has been added .
Optimizer ( stay 1 . 1 in )
stay 1.1 in , We exposed the constraint optimizer . You can do this by placing the tag app:layout_optimizationLevel Add to ConstraintLayout Element to determine which optimizations to apply .
- none: Do not apply optimization
- standard : Default . Optimize only direct and obstacle constraints
- direct: Optimize direct constraints
- obstacle : Optimize obstacle constraints
- chain : Optimize chain constraints ( experiment )
- dimension : Optimize dimension measurement ( experimental ), Reduce the number of metrics that match constraint elements
This attribute is a mask , So you can decide to turn a particular optimization on or off by listing the optimizations you want . for example :app:layout_optimizationLevel=“direct|barrier|chain”
边栏推荐
- Oracle/PLSQL: Length Function
- TopoLVM: 基于LVM的Kubernetes本地持久化方案,容量感知,动态创建PV,轻松使用本地磁盘
- Precautions for using sneakemake
- CVPR2022 | PointDistiller:面向高效紧凑3D检测的结构化知识蒸馏
- jwt的认证流程和使用案例
- I earned 3W yuan a month from my sideline: the industry you despise really makes money!
- memcached基础14
- "All majors are persuading them to quit." is it actually the most friendly to college students?
- P5.js death planet
- 谷歌开始卷自己,AI架构Pathways加持,推出200亿生成模型
猜你喜欢

博日科技招股书失效,中金公司已停止对其辅导,放弃港交所上市?

别被洗脑了,这才是90%中国人的工资真相

Browser cache

Detailed explanation of ThreadLocal
在 IDEA 里看个书很过分嘛!

Bs-gx-016 implementation of textbook management system based on SSM

Press key to control LED status reversal

dat. gui. JS star circle track animation JS special effect

1.44寸TFT-LCD显示屏取模教程

Pointer compression for JVM
随机推荐
Oracle/PLSQL: To_ Clob Function
图论知识及其应用初步调研
P5.js death planet
three. JS domino JS special effect
Memcached foundations 12
memcached基础10
【系统分析师之路】第六章 复盘需求工程(案例论文)
memcached基础13
递归是会更秀strtok
Summary of config mechanism and methods in UVM (2)
热议:月薪1.8万却毫无意义的工作,你干吗?
执念斩长河暑期规划
Memcached Foundation 12
SystemVerilog simulation speed increase
两个页面之间传参方法
二叉樹oj題目
hibernate 根据方言生成sql
Would rather go to 996 than stay at home! 24 years old, unemployed for 7 months, worse than work, no work
Memcached foundation 10
二叉树oj题目