สร้าง Guideline ไว้ไกด์ view
Guideline เป็น Helper ของ ConstraintLayout มีลักษณะเป็นเส้นประ ปรากฎตามตำแหน่งที่กำหนดอิงจาก screen ใช้สำหรับให้ view ยึดเกาะได้
** เส้น Guideline จะแสดงให้เห็นขณะ dev เท่านั้น ไม่แสดงบน Device
เมื่อไหร่ถึงใช้ Guideline ?
- ต้องการยึด view อยู่ในตำแหน่งตามสัดส่วนของหน้าจอ
- ต้องการ set margin start หรือ end ให้กับหลายๆ view ก็เปลี่ยนมายึดติดกับ guideline ตัวเดียวแทน ตามรูปด้านล่าง
ตัวอย่างการใช้ Guideline (เส้นประสีแดง)
Attribute ที่ใช้งาน
- กำหนด Orientation
android:orientation="{vertical หรือ horizontal}"
- กำหนดตำแหน่ง
1. Percent - เส้น Guideline อยู่ตำแหน่งเปอร์เซ็นต์ตามขนาดความกว้าง หรือ
ความสูงของหน้าจอ มีค่า 0 -> 1
0 = 0%
0.5 = 50%
0.7 = 70%
1 = 100%
app:layout_constraintGuide_percent="{0 ถึง 1}"
2. Begin - เส้น Guideline ห่างจากตำแหน่ง start = {dp}
app:layout_constraintGuide_begin="{dp}"
3. End - เส้น Guideline ห่างจากตำแหน่ง end= {dp}
app:layout_constraintGuide_end="{dp}"
รูปแบบการใช้งาน
- กำหนด Orientation
android:orientation="vertical"
หรือ
android:orientation="horizontal"
- กำหนดตำแหน่ง
app:layout_constraintGuide_percent="0.7"
หรือ
app:layout_constraintGuide_begin="250dp"
หรือ
app:layout_constraintGuide_end="44dp"
Create Guideline
คลิกขวาที่ view > Helpers > เลือก Guideline แบบ vertical หรือ Horizontal
ตัวอย่างการใช้งานแบบ 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">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline" />
</androidx.constraintlayout.widget.ConstraintLayout>
ผลลัพธ์
เป็นยังไงกันบ้างค่ะ สำหรับการใช้งาน Guideline ในรูปแบบต่างๆ ไม่ยากอย่างที่คิด ลองนำไปกันดูนะคะ^^