RelativeLayout——相对布局

来源:互联网 发布:java从键盘输入字符串 编辑:程序博客网 时间:2024/05/20 11:47

相对布局RelativeLayout是指按照组件之间的相对位置进行布局,如一个组件在另一个组件的左右上下等等。这是很常用的布局,它灵活、可以实现很适配性强的布局。所以用好它可以使你在UI设计中游刃有余。RelativeLayout中可以设置的属性不多,很多属性都是设置在子View中的,这些属性在RelativeLayout.LayoutParams这个内部类里,可以去SDK里面看看。

1. android:gravity

这个属性和LinearLayout里的一样,请参考LinearLayout——线性布局(上)

2. android:ignoregravity

设置那个子View不适用RelativeLayout里设置的gravity属性

实例代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center_horizontal"    android:ignoreGravity="@+id/test" >    <Button        android:id="@+id/test"        android:layout_width="100dp"        android:layout_height="100dp"        android:text="ABCD" />    <Button        android:layout_width="100dp"        android:layout_height="100dp"        android:text="1234" /></RelativeLayout>

效果图: 如果不设置ignoregravity那么两个子View将在父布局水平中间重叠



3. RelativeLayout.LayoutParams属性



这个表全面的讲述了RelativeLayout.LayoutParams中的属性,其中需要特别注意的是android:layout_alignWithParentIfMissing,这个属性在有的时候很有用。

4. 使用技巧

场景一: 如果一个view的width是wrap_content,而另一个布局的width要和他一样
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"  >    <TextView        android:id="@+id/t1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="AAAAAAA" />        <TextView        android:layout_alignLeft="@+id/t1"        android:layout_alignRight="@+id/t1"        android:layout_below="@+id/t1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="BBBBBBBBBBBB" /></RelativeLayout>
注意第二个TextView的头两行

效果图:

待添加...

相对布局的种种妙用还是要多多使用才能体会的,希望大家能在布局的时候首先想到RelativeLayout,而不要一味的使用LinearLayout。