Constraint Layout
🧱 ConstraintLayout কী?
ConstraintLayout হলো একটি flexible ViewGroup, যা:
Child views কে parent বা অন্যান্য views এর সাথে constraints ব্যবহার করে স্থাপন করতে দেয়।
-
Layout কে খুব সহজে responsive ও adaptive করা যায় — অর্থাৎ, বিভিন্ন screen size এ ঠিকঠাক কাজ করে।
-
RelativeLayout এর মত sibling-reference ব্যবহার করে views স্থাপন করা যায়, কিন্তু আরও বেশি control দেয়।
🧩 ConstraintLayout-এর মূল বৈশিষ্ট্য
-
Vertical এবং Horizontal Constraints
প্রতিটি view কে top, bottom, start, end constraints দিয়ে parent বা অন্য views এর সাথে যুক্ত করা যায়।
-
উদাহরণ:
view কে parent top এর সাথে attach করা
-
view কে অন্য view এর ডান পাশে attach করা
-
Sibling Reference
-
RelativeLayout এর মতো, যদি অন্য view এর সাথে relative অবস্থান দিতে চাও, view-এর ID ব্যবহার করতে হবে।
-
-
Negative Margin Support
-
ConstraintLayout এ margin negative দেওয়া যায়, অর্থাৎ view টাকে একটু parent বা sibling এর বাহিরে ঠেলে দেওয়া যায়।
-
-
Bias (0% - 100%)
Horizontal বা vertical orientation এ view কে নির্দিষ্ট পরিমাণে shift করতে bias ব্যবহার করা হয়।
-
উদাহরণ:
app:layout_constraintHorizontal_bias="0.33"👉 এখানে view parent এর horizontal space এর 33% অবস্থানে যাবে।
-
Flexible & Modern UI
LinearLayout বা RelativeLayout থেকে অনেক compact এবং efficient
-
Nested layout দরকার হয় না, তাই performance ভালো
📄 একটি উদাহরণ
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
app:layout_constraintTop_toBottomOf="@id/button1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.33"
android:layout_marginTop="16dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
🔍 ব্যাখ্যা
-
button1parent এর top-left corner এ আছে 16dp margin সহ। -
button2button1এর নিচে আছে, কিন্তু horizontal_bias=0.33 এর কারণে এটি left থেকে 33% অবস্থানে চলে গেছে। -
ConstraintLayout parent ও sibling references ব্যবহার করে precise positioning দেয়।
🧠 ConstraintLayout এর সুবিধা
| সুবিধা | ব্যাখ্যা |
|---|---|
| Flexible positioning | parent বা sibling-relative positioning |
| Bias | view কে fractional position এ রাখা যায় (0%-100%) |
| Negative margin | view কে slightly বাহিরে ঠেলা যায় |
| Less nesting | LinearLayout/RelativeLayout nested layout এর তুলনায় performance ভালো |
| Modern UI | responsive layouts সহজে বানানো যায় |