一、RelativeLayout簡介
RelativeLayout屬於Android中的布局屬性,也稱為相對布局,是GridLayout、TableLayout的父類。它可以讓控件之間的位置相對於父容器或其他控件進行布局,比較靈活。
二、RelativeLayout的特點
RelativeLayout的特點主要有以下幾點:
1、可以方便的控制控件的位置;
2、允許控件根據其他控件的位置進行定位;
3、支持嵌套其它布局方式。
三、控件位置屬性
RelativeLayout通過指定控件之間的相對位置,來決定控件在布局中的位置。RelativeLayout的控件位置屬性有以下幾種:
1、android:layout_alignParentTop
控制控件的上邊緣與布局的上邊緣對齊。
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:src="@drawable/image" />
2、android:layout_alignParentBottom
控制控件的下邊緣與布局的下邊緣對齊。
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="Bottom" />
3、android:layout_alignParentLeft
控制控件的左邊緣與布局的左邊緣對齊。
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Left" android:layout_alignParentLeft="true" />
4、android:layout_alignParentRight
控制控件的右邊緣與布局的右邊緣對齊。
<EditText android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" />
5、android:layout_centerInParent
控制控件的中心點與父布局的中心點對齊。
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/image" android:layout_centerInParent="true"/>
6、android:layout_above
控制控件在指定控件之上。
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Above" android:layout_above="@+id/bottom"/> <Button android:id="@+id/bottom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bottom"/>
7、android:layout_below
控制控件在指定控件之下。
<Button android:id="@+id/top" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Top"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Below" android:layout_below="@id/top"/>
四、嵌套使用
RelativeLayout可以和其他布局方式進行嵌套使用,比如在一個RelativeLayout中嵌套一個LinearLayout。
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_alignParentBottom="true"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OK" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_centerInParent="true" /> </RelativeLayout>
五、總結
RelativeLayout是Android中比較靈活的布局方式,可以根據控件之間相對位置進行布局。通過上述介紹,我們可以對RelativeLayout的各種屬性有了更全面的了解。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243463.html