Best Practices for UI Layout Design in Android using Constraint Layout
Constraints
If we don't specify the position of the View, the View will always appear in the position 0,0 in the parent which is top-left corner. There are different ways to position.
- Absolute Position : we specify the coordinates of a view in the coordinate system of the parent Eg. layout_margin
- Relative Position : we specify where the view goes in relation to other views, including the parent.
Views can relate to each other using fixed constraints such as margins.
Adaptable Constraints : where we specify a relationship between views, and the system figures out where the views end up. Eg. adding a flexible constraints to the each edge of the parent centers the view because it is connected equally to both edges. constraints_starttostartof ....
Ratios
We can also define one-dimension of a rigid as the ratio of other dimension. Eg. we can make a square making 1:1 ratio
How to do?
- We constrain either the width or height and set the other dimension to 0dp to signal that it will be calculated.
- We set the attribute layout constraints dimension ratio to specify width to height ratio.
<Button
android:id="@+id/simpleBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:text="Button"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
Ratios are very powerful for creating adaptive layout because you don't have to hardcode the dimensions to get the same aspect ratio on each device.
Chaining
Chain link together Views in a Horizontal or Vertical row and then they behave as a group. A set of views are considered a chain if they are linked together via a bidirectional connection.
Eg. start_toEndOf + end_toStartOf
Chains are controlled by attributes set on the head of the chain. The head is the element from which the chain was created.
- The default behaviour of the chain is to spread the elements equally in the available space.
- By assigning weight and bias to elements, you can control how they align.
- Spread Chain - is the default and spreads elements equally
- Spread Inside Chain - will uses all available space with a head and tail glued to the parent.
- Weighted Chain - will use up all space and resize elements to fill it, based on the values set in the layout constraint horizontal weight or layout constraint vertical weight attributes.
- Packed Chain - will do the opposite and use the minimum space.
Comments
Post a Comment