-
Notifications
You must be signed in to change notification settings - Fork 176
/
ConstraintLayout.java
3679 lines (3388 loc) · 164 KB
/
ConstraintLayout.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.widget;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.core.LinearSystem;
import androidx.constraintlayout.core.Metrics;
import androidx.constraintlayout.core.widgets.ConstraintAnchor;
import androidx.constraintlayout.core.widgets.ConstraintWidget;
import androidx.constraintlayout.core.widgets.ConstraintWidgetContainer;
import androidx.constraintlayout.core.widgets.Guideline;
import androidx.constraintlayout.core.widgets.Optimizer;
import androidx.constraintlayout.core.widgets.analyzer.BasicMeasure;
import androidx.core.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import static androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.*;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
/**
* A {@code ConstraintLayout} is a {@link android.view.ViewGroup} which allows you
* to position and size widgets in a flexible way.
* <p>
* <b>Note:</b> {@code ConstraintLayout} is available as a support library that you can use
* on Android systems starting with API level 9 (Gingerbread).
* As such, we are planning on enriching its API and capabilities over time.
* This documentation will reflect those changes.
* </p>
* <p>
* There are currently various types of constraints that you can use:
* <ul>
* <li>
* <a href="#RelativePositioning">Relative positioning</a>
* </li>
* <li>
* <a href="#Margins">Margins</a>
* </li>
* <li>
* <a href="#CenteringPositioning">Centering positioning</a>
* </li>
* <li>
* <a href="#CircularPositioning">Circular positioning</a>
* </li>
* <li>
* <a href="#VisibilityBehavior">Visibility behavior</a>
* </li>
* <li>
* <a href="#DimensionConstraints">Dimension constraints</a>
* </li>
* <li>
* <a href="#Chains">Chains</a>
* </li>
* <li>
* <a href="#VirtualHelpers">Virtual Helpers objects</a>
* </li>
* <li>
* <a href="#Optimizer">Optimizer</a>
* </li>
* </ul>
* </p>
*
* <p>
* Note that you cannot have a circular dependency in constraints.
* </p>
* <p>
* Also see {@link ConstraintLayout.LayoutParams
* ConstraintLayout.LayoutParams} for layout attributes
* </p>
*
* <div class="special reference">
* <h3>Developer Guide</h3>
*
* <h4 id="RelativePositioning"> Relative positioning </h4>
* <p>
* Relative positioning is one of the basic building blocks of creating layouts in ConstraintLayout.
* Those constraints allow you to position a given widget relative to another one. You can constrain
* a widget on the horizontal and vertical axis:
* <ul>
* <li>Horizontal Axis: left, right, start and end sides</li>
* <li>Vertical Axis: top, bottom sides and text baseline</li>
* </ul>
* <p>
* The general concept is to constrain a given side of a widget to another side of any other widget.
* <p>
* For example, in order to position button B to the right of button A (Fig. 1):
* <br><div align="center">
* <img width="300px" src="resources/images/relative-positioning.png">
* <br><b><i>Fig. 1 - Relative Positioning Example</i></b>
* </div>
* </p>
* <p>
* you would need to do:
* </p>
* <pre>{@code
* <Button android:id="@+id/buttonA" ... />
* <Button android:id="@+id/buttonB" ...
* app:layout_constraintLeft_toRightOf="@+id/buttonA" />
* }
* </pre>
* This tells the system that we want the left side of button B to be constrained to the right side of button A.
* Such a position constraint means that the system will try to have both sides share the same location.
* <br><div align="center" >
* <img width="350px" src="resources/images/relative-positioning-constraints.png">
* <br><b><i>Fig. 2 - Relative Positioning Constraints</i></b>
* </div>
*
* <p>Here is the list of available constraints (Fig. 2):</p>
* <ul>
* <li>{@code layout_constraintLeft_toLeftOf}</li>
* <li>{@code layout_constraintLeft_toRightOf}</li>
* <li>{@code layout_constraintRight_toLeftOf}</li>
* <li>{@code layout_constraintRight_toRightOf}</li>
* <li>{@code layout_constraintTop_toTopOf}</li>
* <li>{@code layout_constraintTop_toBottomOf}</li>
* <li>{@code layout_constraintBottom_toTopOf}</li>
* <li>{@code layout_constraintBottom_toBottomOf}</li>
* <li>{@code layout_constraintBaseline_toBaselineOf}</li>
* <li>{@code layout_constraintStart_toEndOf}</li>
* <li>{@code layout_constraintStart_toStartOf}</li>
* <li>{@code layout_constraintEnd_toStartOf}</li>
* <li>{@code layout_constraintEnd_toEndOf}</li>
* </ul>
* <p>
* They all take a reference {@code id} to another widget, or the {@code parent} (which will reference the parent container, i.e. the ConstraintLayout):
* <pre>{@code
* <Button android:id="@+id/buttonB" ...
* app:layout_constraintLeft_toLeftOf="parent" />
* }
* </pre>
*
* </p>
*
* <h4 id="Margins"> Margins </h4>
* <p>
* <div align="center" >
* <img width="325px" src="resources/images/relative-positioning-margin.png">
* <br><b><i>Fig. 3 - Relative Positioning Margins</i></b>
* </div>
* <p>If side margins are set, they will be applied to the corresponding constraints (if they exist) (Fig. 3), enforcing
* the margin as a space between the target and the source side. The usual layout margin attributes can be used to this effect:
* <ul>
* <li>{@code android:layout_marginStart}</li>
* <li>{@code android:layout_marginEnd}</li>
* <li>{@code android:layout_marginLeft}</li>
* <li>{@code android:layout_marginTop}</li>
* <li>{@code android:layout_marginRight}</li>
* <li>{@code android:layout_marginBottom}</li>
* <li>{@code layout_marginBaseline}</li>
* </ul>
* <p>Note that a margin can only be positive or equal to zero, and takes a {@code Dimension}.</p>
* <h4 id="GoneMargin"> Margins when connected to a GONE widget</h4>
* <p>When a position constraint target's visibility is {@code View.GONE}, you can also indicate a different
* margin value to be used using the following attributes:</p>
* <ul>
* <li>{@code layout_goneMarginStart}</li>
* <li>{@code layout_goneMarginEnd}</li>
* <li>{@code layout_goneMarginLeft}</li>
* <li>{@code layout_goneMarginTop}</li>
* <li>{@code layout_goneMarginRight}</li>
* <li>{@code layout_goneMarginBottom}</li>
* <li>{@code layout_goneMarginBaseline}</li>
* </ul>
* </p>
*
* </p>
* <h4 id="CenteringPositioning"> Centering positioning and bias</h4>
* <p>
* A useful aspect of {@code ConstraintLayout} is in how it deals with "impossible" constraints. For example, if
* we have something like:
* <pre>{@code
* <androidx.constraintlayout.widget.ConstraintLayout ...>
* <Button android:id="@+id/button" ...
* app:layout_constraintLeft_toLeftOf="parent"
* app:layout_constraintRight_toRightOf="parent"/>
* </>
* }
* </pre>
* </p>
* <p>
* Unless the {@code ConstraintLayout} happens to have the exact same size as the {@code Button}, both constraints
* cannot be satisfied at the same time (both sides cannot be where we want them to be).
* <p><div align="center" >
* <img width="325px" src="resources/images/centering-positioning.png">
* <br><b><i>Fig. 4 - Centering Positioning</i></b>
* </div>
* <p>
* What happens in this case is that the constraints act like opposite forces
* pulling the widget apart equally (Fig. 4); such that the widget will end up being centered in the parent container.
* This will apply similarly for vertical constraints.
* </p>
* <h5 id="Bias">Bias</h5>
* <p>
* The default when encountering such opposite constraints is to center the widget; but you can tweak
* the positioning to favor one side over another using the bias attributes:
* <ul>
* <li>{@code layout_constraintHorizontal_bias}</li>
* <li>{@code layout_constraintVertical_bias}</li>
* </ul>
* <p><div align="center" >
* <img width="325px" src="resources/images/centering-positioning-bias.png">
* <br><b><i>Fig. 5 - Centering Positioning with Bias</i></b>
* </div>
* <p>
* For example the following will make the left side with a 30% bias instead of the default 50%, such that the left side will be
* shorter, with the widget leaning more toward the left side (Fig. 5):
* </p>
* <pre>{@code
* <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"/>
* </>
* }
* </pre>
* Using bias, you can craft User Interfaces that will better adapt to screen sizes changes.
* </p>
* </p>
*
* <h4 id="CircularPositioning"> Circular positioning (<b>Added in 1.1</b>)</h4>
* <p>
* You can constrain a widget center relative to another widget center, at an angle and a distance. This allows
* you to position a widget on a circle (see Fig. 6). The following attributes can be used:
* <ul>
* <li>{@code layout_constraintCircle} : references another widget id</li>
* <li>{@code layout_constraintCircleRadius} : the distance to the other widget center</li>
* <li>{@code layout_constraintCircleAngle} : which angle the widget should be at (in degrees, from 0 to 360)</li>
* </ul>
* <p><div align="center" >
* <img width="325px" src="resources/images/circle1.png">
* <img width="325px" src="resources/images/circle2.png">
* <br><b><i>Fig. 6 - Circular Positioning</i></b>
* </div>
* <br><br>
* <pre>{@code
* <Button android:id="@+id/buttonA" ... />
* <Button android:id="@+id/buttonB" ...
* app:layout_constraintCircle="@+id/buttonA"
* app:layout_constraintCircleRadius="100dp"
* app:layout_constraintCircleAngle="45" />
* }
* </pre>
* </p>
* <h4 id="VisibilityBehavior"> Visibility behavior </h4>
* <p>
* {@code ConstraintLayout} has a specific handling of widgets being marked as {@code View.GONE}.
* <p>{@code GONE} widgets, as usual, are not going to be displayed and are not part of the layout itself (i.e. their actual dimensions
* will not be changed if marked as {@code GONE}).
*
* <p>But in terms of the layout computations, {@code GONE} widgets are still part of it, with an important distinction:
* <ul>
* <li> For the layout pass, their dimension will be considered as zero (basically, they will be resolved to a point)</li>
* <li> If they have constraints to other widgets they will still be respected, but any margins will be as if equals to zero</li>
* </ul>
*
* <p><div align="center" >
* <img width="350px" src="resources/images/visibility-behavior.png">
* <br><b><i>Fig. 7 - Visibility Behavior</i></b>
* </div>
* <p>This specific behavior allows to build layouts where you can temporarily mark widgets as being {@code GONE},
* without breaking the layout (Fig. 7), which can be particularly useful when doing simple layout animations.
* <p><b>Note: </b>The margin used will be the margin that B had defined when connecting to A (see Fig. 7 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 (see <a href="#GoneMargin">the section above about the gone margin attributes</a>).
* </p>
*
* <h4 id="DimensionConstraints"> Dimensions constraints </h4>
* <h5>Minimum dimensions on ConstraintLayout</h5>
* <p>
* You can define minimum and maximum sizes for the {@code ConstraintLayout} itself:
* <ul>
* <li>{@code android:minWidth} set the minimum width for the layout</li>
* <li>{@code android:minHeight} set the minimum height for the layout</li>
* <li>{@code android:maxWidth} set the maximum width for the layout</li>
* <li>{@code android:maxHeight} set the maximum height for the layout</li>
* </ul>
* Those minimum and maximum dimensions will be used by {@code ConstraintLayout} when its dimensions are set to {@code WRAP_CONTENT}.
* </p>
* <h5>Widgets dimension constraints</h5>
* <p>
* The dimension of the widgets can be specified by setting the {@code android:layout_width} and
* {@code android:layout_height} attributes in 3 different ways:
* <ul>
* <li>Using a specific dimension (either a literal value such as {@code 123dp} or a {@code Dimension} reference)</li>
* <li>Using {@code WRAP_CONTENT}, which will ask the widget to compute its own size</li>
* <li>Using {@code 0dp}, which is the equivalent of "{@code MATCH_CONSTRAINT}"</li>
* </ul>
* <p><div align="center" >
* <img width="325px" src="resources/images/dimension-match-constraints.png">
* <br><b><i>Fig. 8 - Dimension Constraints</i></b>
* </div>
* The first two works in a similar fashion as other layouts. The last one will resize the widget in such a way as
* matching the constraints that are set (see Fig. 8, (a) is wrap_content, (b) is 0dp). If margins are set, they will be taken in account
* in the computation (Fig. 8, (c) with 0dp).
* <p>
* <b>Important: </b> {@code MATCH_PARENT} is not recommended for widgets contained in a {@code ConstraintLayout}. Similar behavior can
* be defined by using {@code MATCH_CONSTRAINT} with the corresponding left/right or top/bottom constraints being set to {@code "parent"}.
* </p>
* </p>
* <h5>WRAP_CONTENT : enforcing constraints (<i><b>Added in 1.1</b></i>)</h5>
* <p>
* If a dimension is set to {@code WRAP_CONTENT}, in versions before 1.1 they will be treated as a literal dimension -- meaning, constraints will
* not limit the resulting dimension. While in general this is enough (and faster), in some situations, you might want to use {@code WRAP_CONTENT},
* yet keep enforcing constraints to limit the resulting dimension. In that case, you can add one of the corresponding attribute:
* <ul>
* <li>{@code app:layout_constrainedWidth="true|false"}</li>
* <li>{@code app:layout_constrainedHeight="true|false"}</li>
* </ul>
* </p>
* <h5>MATCH_CONSTRAINT dimensions (<i><b>Added in 1.1</b></i>)</h5>
* <p>
* When a dimension is set to {@code MATCH_CONSTRAINT}, the default behavior is to have the resulting size take all the available space.
* Several additional modifiers are available:
* <ul>
* <li>{@code layout_constraintWidth_min} and {@code layout_constraintHeight_min} : will set the minimum size for this dimension</li>
* <li>{@code layout_constraintWidth_max} and {@code layout_constraintHeight_max} : will set the maximum size for this dimension</li>
* <li>{@code layout_constraintWidth_percent} and {@code layout_constraintHeight_percent} : will set the size of this dimension as a percentage of the parent</li>
* </ul>
* <h6>Min and Max</h6>
* The value indicated for min and max can be either a dimension in Dp, or "wrap", which will use the same value as what {@code WRAP_CONTENT} would do.
* <h6>Percent dimension</h6>
* To use percent, you need to set the following:
* <ul>
* <li>The dimension should be set to {@code MATCH_CONSTRAINT} (0dp)</li>
* <li>The default should be set to percent {@code app:layout_constraintWidth_default="percent"}
* or {@code app:layout_constraintHeight_default="percent"}</li>
* <li>Then set the {@code layout_constraintWidth_percent}
* or {@code layout_constraintHeight_percent} attributes to a value between 0 and 1</li>
* </ul>
* </p>
* <h5>Ratio</h5>
* <p>
* You can also define one dimension of a widget as a ratio of the other one. In order to do that, you
* need to have at least one constrained dimension be set to {@code 0dp} (i.e., {@code MATCH_CONSTRAINT}), and set the
* attribute {@code layout_constraintDimensionRatio} to a given ratio.
* For example:
* <pre>
* {@code
* <Button android:layout_width="wrap_content"
* android:layout_height="0dp"
* app:layout_constraintDimensionRatio="1:1" />
* }
* </pre>
* will set the height of the button to be the same as its width.
* </p>
* <p> The ratio can be expressed either as:
* <ul>
* <li>a float value, representing a ratio between width and height</li>
* <li>a ratio in the form "width:height"</li>
* </ul>
* </p>
* <p>
* You can also use ratio if both dimensions are set to {@code MATCH_CONSTRAINT} (0dp). In this case the system sets the
* largest dimensions that satisfies all constraints and maintains the aspect ratio specified. To constrain one specific side
* based on the dimensions of another, you can pre append {@code W,}" or {@code H,} to constrain the width or height
* respectively.
* For example,
* If one dimension is constrained by two targets (e.g. width is 0dp and centered on parent) you can indicate which
* side should be constrained, by adding the letter {@code W} (for constraining the width) or {@code H}
* (for constraining the height) in front of the ratio, separated
* by a comma:
* <pre>
* {@code
* <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"/>
* }
* </pre>
* will set the height of the button following a 16:9 ratio, while the width of the button will match the constraints
* to its parent.
*
* </p>
*
* <h4 id="Chains">Chains</h4>
* <p>Chains provide group-like behavior in a single axis (horizontally or vertically). The other axis can be constrained independently.</p>
* <h5>Creating a chain</h5>
* <p>
* A set of widgets are considered a chain if they are linked together via a bi-directional connection (see Fig. 9, showing a minimal chain, with two widgets).
* </p>
* <p><div align="center" >
* <img width="325px" src="resources/images/chains.png">
* <br><b><i>Fig. 9 - Chain</i></b>
* </div>
* <p>
* <h5>Chain heads</h5>
* <p>
* Chains are controlled by attributes set on the first element of the chain (the "head" of the chain):
* </p>
* <p><div align="center" >
* <img width="400px" src="resources/images/chains-head.png">
* <br><b><i>Fig. 10 - Chain Head</i></b>
* </div>
* <p>The head is the left-most widget for horizontal chains, and the top-most widget for vertical chains.</p>
* <h5>Margins in chains</h5>
* <p>If margins are specified on connections, they will be taken into account. In the case of spread chains, margins will be deducted from the allocated space.</p>
* <h5>Chain Style</h5>
* <p>When setting the attribute {@code layout_constraintHorizontal_chainStyle} or {@code layout_constraintVertical_chainStyle} on the first element of a chain,
* the behavior of the chain will change according to the specified style (default is {@code CHAIN_SPREAD}).
* <ul>
* <li>{@code CHAIN_SPREAD} -- the elements will be spread out (default style)</li>
* <li>Weighted chain -- in {@code CHAIN_SPREAD} mode, if some widgets are set to {@code MATCH_CONSTRAINT}, they will split the available space</li>
* <li>{@code CHAIN_SPREAD_INSIDE} -- similar, but the endpoints of the chain will not be spread out</li>
* <li>{@code CHAIN_PACKED} -- the elements of the chain will be packed together. The horizontal or vertical
* bias attribute of the child will then affect the positioning of the packed elements</li>
* </ul>
* <p><div align="center" >
* <img width="600px" src="resources/images/chains-styles.png">
* <br><b><i>Fig. 11 - Chains Styles</i></b>
* </div>
* </p>
* <h5>Weighted chains</h5>
* <p>The default behavior of a chain is to spread the elements equally in the available space. If one or more elements are using {@code MATCH_CONSTRAINT}, they
* will use the available empty space (equally divided among themselves). The attribute {@code layout_constraintHorizontal_weight} and {@code layout_constraintVertical_weight}
* will control how the space will be distributed among the elements using {@code MATCH_CONSTRAINT}. For example, on a chain containing two elements using {@code MATCH_CONSTRAINT},
* with the first element using a weight of 2 and the second a weight of 1, the space occupied by the first element will be twice that of the second element.</p>
*
* <h5>Margins and chains (<i><b>in 1.1</b></i>)</h5>
* <p>When using margins on elements in a chain, the margins are additive.</p>
* <p>For example, on a horizontal chain, if one element defines a right margin of 10dp and the next element
* defines a left margin of 5dp, the resulting margin between those two elements is 15dp.</p>
* <p>An item plus its margins are considered together when calculating leftover space used by chains
* to position items. The leftover space does not contain the margins.</p>
*
* <h4 id="VirtualHelpers"> Virtual Helper objects </h4>
* <p>In addition to the intrinsic capabilities detailed previously, you can also use special helper objects
* in {@code ConstraintLayout} to help you with your layout. Currently, the {@code Guideline}{@see Guideline} object allows you to create
* Horizontal and Vertical guidelines which are positioned relative to the {@code ConstraintLayout} container. Widgets can
* then be positioned by constraining them to such guidelines. In <b>1.1</b>, {@code Barrier} and {@code Group} were added too.</p>
*
* <h4 id="Optimizer">Optimizer (<i><b>in 1.1</b></i>)</h4>
* <p>
* In 1.1 we exposed the constraints optimizer. You can decide which optimizations are applied by adding the tag <i>app:layout_optimizationLevel</i> to the ConstraintLayout element.
* <ul>
* <li><b>none</b> : no optimizations are applied</li>
* <li><b>standard</b> : Default. Optimize direct and barrier constraints only</li>
* <li><b>direct</b> : optimize direct constraints</li>
* <li><b>barrier</b> : optimize barrier constraints</li>
* <li><b>chain</b> : optimize chain constraints (experimental)</li>
* <li><b>dimensions</b> : optimize dimensions measures (experimental), reducing the number of measures of match constraints elements</li>
* </ul>
* </p>
* <p>This attribute is a mask, so you can decide to turn on or off specific optimizations by listing the ones you want.
* For example: <i>app:layout_optimizationLevel="direct|barrier|chain"</i> </p>
* </div>
*/
public class ConstraintLayout extends ViewGroup {
/**
* @suppress
*/
public static final String VERSION = "ConstraintLayout-2.1.2";
private static final String TAG = "ConstraintLayout";
private static final boolean USE_CONSTRAINTS_HELPER = true;
private static final boolean DEBUG = LinearSystem.FULL_DEBUG;
private static final boolean DEBUG_DRAW_CONSTRAINTS = false;
private static final boolean MEASURE = false;
private static final boolean OPTIMIZE_HEIGHT_CHANGE = false;
SparseArray<View> mChildrenByIds = new SparseArray<>();
// This array keep a list of helper objects if they are present
private ArrayList<ConstraintHelper> mConstraintHelpers = new ArrayList<>(4);
protected ConstraintWidgetContainer mLayoutWidget = new ConstraintWidgetContainer();
private int mMinWidth = 0;
private int mMinHeight = 0;
private int mMaxWidth = Integer.MAX_VALUE;
private int mMaxHeight = Integer.MAX_VALUE;
protected boolean mDirtyHierarchy = true;
private int mOptimizationLevel = Optimizer.OPTIMIZATION_STANDARD;
private ConstraintSet mConstraintSet = null;
protected ConstraintLayoutStates mConstraintLayoutSpec = null;
private int mConstraintSetId = -1;
private HashMap<String, Integer> mDesignIds = new HashMap<>();
// Cache last measure
private int mLastMeasureWidth = -1;
private int mLastMeasureHeight = -1;
int mLastMeasureWidthSize = -1;
int mLastMeasureHeightSize = -1;
int mLastMeasureWidthMode = MeasureSpec.UNSPECIFIED;
int mLastMeasureHeightMode = MeasureSpec.UNSPECIFIED;
private SparseArray<ConstraintWidget> mTempMapIdToWidget = new SparseArray<>();
/**
* @suppress
*/
public final static int DESIGN_INFO_ID = 0;
private ConstraintsChangedListener mConstraintsChangedListener;
private Metrics mMetrics;
private static SharedValues sSharedValues = null;
/**
* Returns the SharedValues instance, creating it if it doesn't exist.
*
* @return the SharedValues instance
*/
public static SharedValues getSharedValues() {
if (sSharedValues == null) {
sSharedValues = new SharedValues();
}
return sSharedValues;
}
/**
* @suppress
*/
public void setDesignInformation(int type, Object value1, Object value2) {
if (type == DESIGN_INFO_ID && value1 instanceof String && value2 instanceof Integer) {
if (mDesignIds == null) {
mDesignIds = new HashMap<>();
}
String name = (String) value1;
int index = name.indexOf("/");
if (index != -1) {
name = name.substring(index + 1);
}
int id = (Integer) value2;
mDesignIds.put(name, id);
}
}
/**
* @suppress
*/
public Object getDesignInformation(int type, Object value) {
if (type == DESIGN_INFO_ID && value instanceof String) {
String name = (String) value;
if (mDesignIds != null && mDesignIds.containsKey(name)) {
return mDesignIds.get(name);
}
}
return null;
}
public ConstraintLayout(@NonNull Context context) {
super(context);
init(null, 0, 0);
}
public ConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public ConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
/**
* @suppress
*/
@Override
public void setId(int id) {
mChildrenByIds.remove(getId());
super.setId(id);
mChildrenByIds.put(getId(), this);
}
// -------------------------------------------------------------------------------------------
// Measure widgets callbacks
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
class Measurer implements BasicMeasure.Measurer {
ConstraintLayout layout;
int paddingTop;
int paddingBottom;
int paddingWidth;
int paddingHeight;
int layoutWidthSpec;
int layoutHeightSpec;
public void captureLayoutInfo(int widthSpec, int heightSpec, int top, int bottom, int width, int height) {
paddingTop = top;
paddingBottom = bottom;
paddingWidth = width;
paddingHeight = height;
layoutWidthSpec = widthSpec;
layoutHeightSpec = heightSpec;
}
public Measurer(ConstraintLayout l) {
layout = l;
}
@SuppressLint("WrongCall")
@Override
public final void measure(ConstraintWidget widget,
BasicMeasure.Measure measure) {
if (widget == null) {
return;
}
if (widget.getVisibility() == GONE && !widget.isInPlaceholder()) {
measure.measuredWidth = 0;
measure.measuredHeight = 0;
measure.measuredBaseline = 0;
return;
}
if (widget.getParent() == null) {
return;
}
long startMeasure;
long endMeasure;
if (MEASURE) {
startMeasure = System.nanoTime();
}
ConstraintWidget.DimensionBehaviour horizontalBehavior = measure.horizontalBehavior;
ConstraintWidget.DimensionBehaviour verticalBehavior = measure.verticalBehavior;
int horizontalDimension = measure.horizontalDimension;
int verticalDimension = measure.verticalDimension;
int horizontalSpec = 0;
int verticalSpec = 0;
int heightPadding = paddingTop + paddingBottom;
int widthPadding = paddingWidth;
View child = (View) widget.getCompanionWidget();
switch (horizontalBehavior) {
case FIXED: {
horizontalSpec = MeasureSpec.makeMeasureSpec(horizontalDimension, MeasureSpec.EXACTLY);
}
break;
case WRAP_CONTENT: {
horizontalSpec = getChildMeasureSpec(layoutWidthSpec, widthPadding, WRAP_CONTENT);
}
break;
case MATCH_PARENT: {
// Horizontal spec must account for margin as well as padding here.
horizontalSpec = getChildMeasureSpec(layoutWidthSpec,
widthPadding + widget.getHorizontalMargin(), LayoutParams.MATCH_PARENT);
}
break;
case MATCH_CONSTRAINT: {
horizontalSpec = getChildMeasureSpec(layoutWidthSpec, widthPadding, WRAP_CONTENT);
boolean shouldDoWrap = widget.mMatchConstraintDefaultWidth == MATCH_CONSTRAINT_WRAP;
if (measure.measureStrategy == BasicMeasure.Measure.TRY_GIVEN_DIMENSIONS
|| measure.measureStrategy == BasicMeasure.Measure.USE_GIVEN_DIMENSIONS) {
// the solver gives us our new dimension, but if we previously had it measured with
// a wrap, it can be incorrect if the other side was also variable.
// So in that case, we have to double-check the other side is stable (else we can't
// just assume the wrap value will be correct).
boolean otherDimensionStable = child.getMeasuredHeight() == widget.getHeight();
boolean useCurrent = measure.measureStrategy == BasicMeasure.Measure.USE_GIVEN_DIMENSIONS
|| !shouldDoWrap
|| (shouldDoWrap && otherDimensionStable)
|| (child instanceof Placeholder)
|| (widget.isResolvedHorizontally());
if (useCurrent) {
horizontalSpec = MeasureSpec.makeMeasureSpec(widget.getWidth(), MeasureSpec.EXACTLY);
}
}
}
break;
}
switch (verticalBehavior) {
case FIXED: {
verticalSpec = MeasureSpec.makeMeasureSpec(verticalDimension, MeasureSpec.EXACTLY);
}
break;
case WRAP_CONTENT: {
verticalSpec = getChildMeasureSpec(layoutHeightSpec,
heightPadding, WRAP_CONTENT);
}
break;
case MATCH_PARENT: {
// Vertical spec must account for margin as well as padding here.
verticalSpec = getChildMeasureSpec(layoutHeightSpec,
heightPadding + widget.getVerticalMargin(), LayoutParams.MATCH_PARENT);
}
break;
case MATCH_CONSTRAINT: {
verticalSpec = getChildMeasureSpec(layoutHeightSpec,
heightPadding, WRAP_CONTENT);
boolean shouldDoWrap = widget.mMatchConstraintDefaultHeight == MATCH_CONSTRAINT_WRAP;
if (measure.measureStrategy == BasicMeasure.Measure.TRY_GIVEN_DIMENSIONS
|| measure.measureStrategy == BasicMeasure.Measure.USE_GIVEN_DIMENSIONS) {
// the solver gives us our new dimension, but if we previously had it measured with
// a wrap, it can be incorrect if the other side was also variable.
// So in that case, we have to double-check the other side is stable (else we can't
// just assume the wrap value will be correct).
boolean otherDimensionStable = child.getMeasuredWidth() == widget.getWidth();
boolean useCurrent = measure.measureStrategy == BasicMeasure.Measure.USE_GIVEN_DIMENSIONS
|| !shouldDoWrap
|| (shouldDoWrap && otherDimensionStable)
|| (child instanceof Placeholder)
|| (widget.isResolvedVertically());
if (useCurrent) {
verticalSpec = MeasureSpec.makeMeasureSpec(widget.getHeight(), MeasureSpec.EXACTLY);
}
}
}
break;
}
ConstraintWidgetContainer container = (ConstraintWidgetContainer) widget.getParent();
if (container != null && Optimizer.enabled(mOptimizationLevel, Optimizer.OPTIMIZATION_CACHE_MEASURES)) {
if (child.getMeasuredWidth() == widget.getWidth()
// note: the container check replicates legacy behavior, but we might want
// to not enforce that in 3.0
&& child.getMeasuredWidth() < container.getWidth()
&& child.getMeasuredHeight() == widget.getHeight()
&& child.getMeasuredHeight() < container.getHeight()
&& child.getBaseline() == widget.getBaselineDistance()
&& !widget.isMeasureRequested()
) {
boolean similar = isSimilarSpec(widget.getLastHorizontalMeasureSpec(), horizontalSpec, widget.getWidth())
&& isSimilarSpec(widget.getLastVerticalMeasureSpec(), verticalSpec, widget.getHeight());
if (similar) {
measure.measuredWidth = widget.getWidth();
measure.measuredHeight = widget.getHeight();
measure.measuredBaseline = widget.getBaselineDistance();
// if the dimensions of the solver widget are already the same as the real view, no need to remeasure.
if (DEBUG) {
System.out.println("SKIPPED " + widget);
}
return;
}
}
}
boolean horizontalMatchConstraints = (horizontalBehavior == ConstraintWidget.DimensionBehaviour.MATCH_CONSTRAINT);
boolean verticalMatchConstraints = (verticalBehavior == ConstraintWidget.DimensionBehaviour.MATCH_CONSTRAINT);
boolean verticalDimensionKnown = (verticalBehavior == ConstraintWidget.DimensionBehaviour.MATCH_PARENT
|| verticalBehavior == ConstraintWidget.DimensionBehaviour.FIXED);
boolean horizontalDimensionKnown = (horizontalBehavior == ConstraintWidget.DimensionBehaviour.MATCH_PARENT
|| horizontalBehavior == ConstraintWidget.DimensionBehaviour.FIXED);
boolean horizontalUseRatio = horizontalMatchConstraints && widget.mDimensionRatio > 0;
boolean verticalUseRatio = verticalMatchConstraints && widget.mDimensionRatio > 0;
if (child == null) {
return;
}
LayoutParams params = (LayoutParams) child.getLayoutParams();
int width = 0;
int height = 0;
int baseline = 0;
if ((measure.measureStrategy == BasicMeasure.Measure.TRY_GIVEN_DIMENSIONS
|| measure.measureStrategy == BasicMeasure.Measure.USE_GIVEN_DIMENSIONS) ||
!(horizontalMatchConstraints && widget.mMatchConstraintDefaultWidth == MATCH_CONSTRAINT_SPREAD
&& verticalMatchConstraints && widget.mMatchConstraintDefaultHeight == MATCH_CONSTRAINT_SPREAD)) {
if (child instanceof VirtualLayout && widget instanceof androidx.constraintlayout.core.widgets.VirtualLayout) {
androidx.constraintlayout.core.widgets.VirtualLayout layout = (androidx.constraintlayout.core.widgets.VirtualLayout) widget;
((VirtualLayout) child).onMeasure(layout, horizontalSpec, verticalSpec);
} else {
child.measure(horizontalSpec, verticalSpec);
}
widget.setLastMeasureSpec(horizontalSpec, verticalSpec);
int w = child.getMeasuredWidth();
int h = child.getMeasuredHeight();
baseline = child.getBaseline();
width = w;
height = h;
if (DEBUG) {
String measurement = MeasureSpec.toString(horizontalSpec) + " x " + MeasureSpec.toString(verticalSpec) + " => " + width + " x " + height;
System.out.println(" (M) measure " + " (" + widget.getDebugName() + ") : " + measurement);
}
if (widget.mMatchConstraintMinWidth > 0) {
width = Math.max(widget.mMatchConstraintMinWidth, width);
}
if (widget.mMatchConstraintMaxWidth > 0) {
width = Math.min(widget.mMatchConstraintMaxWidth, width);
}
if (widget.mMatchConstraintMinHeight > 0) {
height = Math.max(widget.mMatchConstraintMinHeight, height);
}
if (widget.mMatchConstraintMaxHeight > 0) {
height = Math.min(widget.mMatchConstraintMaxHeight, height);
}
boolean optimizeDirect = Optimizer.enabled(mOptimizationLevel, Optimizer.OPTIMIZATION_DIRECT);
if (!optimizeDirect) {
if (horizontalUseRatio && verticalDimensionKnown) {
float ratio = widget.mDimensionRatio;
width = (int) (0.5f + height * ratio);
} else if (verticalUseRatio && horizontalDimensionKnown) {
float ratio = widget.mDimensionRatio;
height = (int) (0.5f + width / ratio);
}
}
if (w != width || h != height) {
if (w != width) {
horizontalSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
if (h != height) {
verticalSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
child.measure(horizontalSpec, verticalSpec);
widget.setLastMeasureSpec(horizontalSpec, verticalSpec);
width = child.getMeasuredWidth();
height = child.getMeasuredHeight();
baseline = child.getBaseline();
if (DEBUG) {
String measurement2 = MeasureSpec.toString(horizontalSpec) + " x " + MeasureSpec.toString(verticalSpec) + " => " + width + " x " + height;
System.out.println("measure (b) " + widget.getDebugName() + " : " + measurement2);
}
}
}
boolean hasBaseline = baseline != -1;
measure.measuredNeedsSolverPass = (width != measure.horizontalDimension)
|| (height != measure.verticalDimension);
if (params.needsBaseline) {
hasBaseline = true;
}
if (hasBaseline && baseline != -1 && widget.getBaselineDistance() != baseline) {
measure.measuredNeedsSolverPass = true;
}
measure.measuredWidth = width;
measure.measuredHeight = height;
measure.measuredHasBaseline = hasBaseline;
measure.measuredBaseline = baseline;
if (MEASURE) {
endMeasure = System.nanoTime();
if (mMetrics != null) {
mMetrics.measuresWidgetsDuration += (endMeasure - startMeasure);
}
}
}
/**
* Returns true if the previous measure spec is equivalent to the new one.
* - if it's the same...
* - if it's not, but the previous was AT_MOST or UNSPECIFIED and the new one
* is EXACTLY with the same size.
*
* @param lastMeasureSpec
* @param spec
* @param widgetSize
* @return
*/
private boolean isSimilarSpec(int lastMeasureSpec, int spec, int widgetSize) {
if (lastMeasureSpec == spec) {
return true;
}
int lastMode = MeasureSpec.getMode(lastMeasureSpec);
int lastSize = MeasureSpec.getSize(lastMeasureSpec);
int mode = MeasureSpec.getMode(spec);
int size = MeasureSpec.getSize(spec);
if (mode == MeasureSpec.EXACTLY
&& (lastMode == MeasureSpec.AT_MOST || lastMode == MeasureSpec.UNSPECIFIED)
&& widgetSize == size) {
return true;
}
return false;
}
@Override
public final void didMeasures() {
final int widgetsCount = layout.getChildCount();
for (int i = 0; i < widgetsCount; i++) {
final View child = layout.getChildAt(i);
if (child instanceof Placeholder) {
((Placeholder) child).updatePostMeasure(layout);
}
}
// TODO refactor into an updatePostMeasure interface
final int helperCount = layout.mConstraintHelpers.size();
if (helperCount > 0) {
for (int i = 0; i < helperCount; i++) {
ConstraintHelper helper = layout.mConstraintHelpers.get(i);
helper.updatePostMeasure(layout);
}
}
}
}
Measurer mMeasurer = new Measurer(this);
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
mLayoutWidget.setCompanionWidget(this);
mLayoutWidget.setMeasurer(mMeasurer);
mChildrenByIds.put(getId(), this);
mConstraintSet = null;
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ConstraintLayout_Layout, defStyleAttr, defStyleRes);
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
if (attr == R.styleable.ConstraintLayout_Layout_android_minWidth) {
mMinWidth = a.getDimensionPixelOffset(attr, mMinWidth);
} else if (attr == R.styleable.ConstraintLayout_Layout_android_minHeight) {
mMinHeight = a.getDimensionPixelOffset(attr, mMinHeight);
} else if (attr == R.styleable.ConstraintLayout_Layout_android_maxWidth) {
mMaxWidth = a.getDimensionPixelOffset(attr, mMaxWidth);
} else if (attr == R.styleable.ConstraintLayout_Layout_android_maxHeight) {
mMaxHeight = a.getDimensionPixelOffset(attr, mMaxHeight);
} else if (attr == R.styleable.ConstraintLayout_Layout_layout_optimizationLevel) {
mOptimizationLevel = a.getInt(attr, mOptimizationLevel);
} else if (attr == R.styleable.ConstraintLayout_Layout_layoutDescription) {
int id = a.getResourceId(attr, 0);
if (id != 0) {
try {
parseLayoutDescription(id);
} catch (Resources.NotFoundException e) {
mConstraintLayoutSpec = null;
}
}
} else if (attr == R.styleable.ConstraintLayout_Layout_constraintSet) {
int id = a.getResourceId(attr, 0);
try {
mConstraintSet = new ConstraintSet();
mConstraintSet.load(getContext(), id);
} catch (Resources.NotFoundException e) {
mConstraintSet = null;
}
mConstraintSetId = id;
}
}
a.recycle();
}
mLayoutWidget.setOptimizationLevel(mOptimizationLevel);
}
/**
* Subclasses can override the handling of layoutDescription
*
* @param id
*/
protected void parseLayoutDescription(int id) {
mConstraintLayoutSpec = new ConstraintLayoutStates(getContext(), this, id);
}
/**
* @suppress
*/
@Override