CONSTRAINT XML LAYOUT BY CODE
CONSTRAINT XML LAYOUT BY CODE
In Android Studio, you can design a CONSTRAINT XML LAYOUT BY CODE using XML code. Here’s an example of how to create a simple ConstraintLayout that contains three TextView elements:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, World!" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a ConstraintLayout example." app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/textView1" app:layout_constraintEnd_toEndOf="parent"/> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This text is aligned to the end of the parent." app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toBottomOf="@id/textView2"/> </androidx.constraintlayout.widget.ConstraintLayout
This code creates a ConstraintLayout that has a width of “match_parent” and a height of “wrap_content”, which means it will take up the full width of the parent container and adjust its height to fit its contents.
Inside the ConstraintLayout, we have three TextView elements. Each TextView has a width of “wrap_content” and a height of “wrap_content”, which means it will adjust its size to fit its contents. The “text” attribute is used to set the text displayed in each TextView.
The key feature of ConstraintLayout is the ability to create constraints between different UI elements and define how they should be positioned on the screen. In the example above, we are using the attributes layout_constraintStart_toStartOf, layout_constraintTop_toTopOf, layout_constraintEnd_toEndOf and layout_constraintBottom_toBottomOf to align the TextViews to the start, top, end and bottom of the parent layout respectively.
You can also set other attributes like layout_constraintWidth, layout_constraintHeight, layout_constraintDimensionRatio, layout_constraintHorizontal_bias, layout_constraintVertical_bias to adjust the behavior of the elements.
Additionally, you can also set layout_margin, layout_padding and layout_gravity attributes to adjust the position and spacing of the elements in the ConstraintLayout.