Android มีทั้ง gravity และ layout_gravity ทำงานต่างกัน:
gravity (android:gravity)
จัดตำแหน่ง **เนื้อหาภายใน View** เอง (เช่น ข้อความใน TextView)
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Click here to hide" />
ข้อความจะอยู่กลาง TextView
ค่าที่ใช้ได้:
- center, center_vertical, center_horizontal
- left, right, start, end
- top, bottom
layout_gravity (android:layout_gravity)
จัดตำแหน่ง **View เองภายใน Parent** (Parent ต้องเป็น LinearLayout หรือ FrameLayout)
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" />
EditText จะชิดขวา Parent
ตัวอย่างเปรียบเทียบ
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Click here to hide" />
</LinearLayout>
ผลลัพธ์
- EditText: ชิดขวา (layout_gravity="right")
- TextView: ข้อความอยู่กลาง (gravity="center")
รูปภาพตัวอย่าง UI ถูกละเว้น