Chain x Weight

Natcha Jintanasatien
te<h @TDG
Published in
1 min readMar 12, 2020
Photo by clevelandclinic

การใช้งาน weight ร่วมกับ chain ใน ConstraintLayout นั้น เหมือนกับการใช้ layout_weight ใน LinearLayout เลยค่ะ

Attribute ที่ใช้งาน

app:layout_constraintHorizontal_weight="{weight}"
app:layout_constraintVertical_weight="{weight}"

ตัวอย่างการใช้งานแบบ Horizontal

<?xml version="1.0" encoding="utf-8"?>
<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">

<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@color/sky"
android:text="TextView1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/textView2"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="TextView2"
android:background="@color/orange"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/textView3"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toEndOf="@+id/textView1"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="TextView3"
android:background="@color/green"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ผลลัพธ์

Horizontal Weight 1–2–3

แบบ Horizontalจะต้องกำหนด android:layout_width=”0dp”
แบบ Vertical จะต้องกำหนด android:layout_height=”0dp”

การนำ weight ใช้งานร่วมกับ chain นั้นไม่ยากเลย ลองนำไปใช้กันดูนะคะ

--

--