一、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/n/243463.html