ต่อเนื่องจากบทความที่แล้วนะครับ ผมได้พูดเกี่ยวกับเรื่องของ LinearLayout ไปแล้ว คราวนี้จะพูดถึงเรื่องของ RelativeLayout กันบ้าง เราได้รู้แล้วว่า LinearLayout นั้นการจัดวาง view ภายในจะเหมือนกับการวางกล่องเรียงไปตามแนวที่เรากำหนด ส่วน RelativeLayout นั้นจะเป็นการวางโดยอ้างอิงจาก View อื่นหรือ อ้างอิงจากตัว RelativeLayout เอง ยกตัวอย่างเช่นมี ImageView อยู่หนึ่งเราอยากวางไว้กึ่งกลางของหน้าจอแล้ววางคำอธิบายไว้ด้านล่างของรูปก็จะสามารถทำได้ดังนี้
สังเกตจาก xml ด้านบน มีการใช้ attribute layout_centerInParent, layout_centerHorizontal, layout_below โดย attribute เหล่านี้จะไม่มีใน LinearLayout โดย ImageView img กำหนดให้ layout_centerInParent = true คือกำหนดให้อยู่กึ่งกลางของ RelativeLayout ซึ่งในตัวอย่างนั้น RelativeLayout มีขนาดเต็มหน้าจอ TextView กำหนด layout_below ="@+id/img" คือกำหนดให้ View นี้อยู่ใต้ view ที่มี id img ซึ่งในตัวอย่างก็คือ ImageView นั่นเอง จากนั้นกำหนด layout_centerHorizontal=true คือกำหนดให้อยู่กึ่งกลางในแนว horizontal ถ้าเป็นแนวตั้งใช้ layout_centerVertical
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/img" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <TextView android:layout_below="@+id/img" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This view is under image" /> </RelativeLayout>หน้าตาก็จะประมาณนี้
สังเกตจาก xml ด้านบน มีการใช้ attribute layout_centerInParent, layout_centerHorizontal, layout_below โดย attribute เหล่านี้จะไม่มีใน LinearLayout โดย ImageView img กำหนดให้ layout_centerInParent = true คือกำหนดให้อยู่กึ่งกลางของ RelativeLayout ซึ่งในตัวอย่างนั้น RelativeLayout มีขนาดเต็มหน้าจอ TextView กำหนด layout_below ="@+id/img" คือกำหนดให้ View นี้อยู่ใต้ view ที่มี id img ซึ่งในตัวอย่างก็คือ ImageView นั่นเอง จากนั้นกำหนด layout_centerHorizontal=true คือกำหนดให้อยู่กึ่งกลางในแนว horizontal ถ้าเป็นแนวตั้งใช้ layout_centerVertical