RelativeLayout布局下实现控件平分空间

起源:使用惯LinearLayout的朋友都知道,若想实现对屏幕的等分,只需要设置Layout_weight的值即可。

可是在RelativeLayout布局下实现等分却不是那么容易。

下面就简单介绍如何在RelativeLayout下实现控件平分空间。

原理简单略带技巧,大家一看就懂。


首先来实现水平等分。

关键在于设置参照物,确定控件的方位。

关键代码如下:

 1     <RelativeLayout

 2         android:layout_width= "match_parent"        

 3         android:layout_height= "120dp">

 4         <!-- 设置参照物 -->

 5         <View

 6             android:id= "@+id/strut"

 7             android:layout_width= "0dp"

 8             android:layout_height= "0dp"

 9             android:layout_centerVertical="true" />

10           

11        <ImageView

12            android:layout_width="match_parent"

13            android:layout_height="match_parent"

14            android:layout_alignBottom="@id/strut"

15            android:layout_alignParentTop="true"

16            android:background="@drawable/bg_red"/>

17 

18        <ImageView

19            android:layout_width="match_parent"

20            android:layout_height="match_parent"

21            android:layout_alignTop="@id/strut"

22            android:layout_alignParentBottom="true"

23            android:background="@drawable/bg_blue"/>            

24     </RelativeLayout >

效果图如下:

RelativeLayout布局下实现控件平分空间

再次来实现垂直等分,原理与水平相似,只是修改方位。

关键代码如下:

 1     <RelativeLayout

 2         android:layout_width= "match_parent"

 3         android:layout_height= "200dp">

 4         <View

 5             android:id= "@+id/strut"

 6             android:layout_width= "0dp"

 7             android:layout_height= "0dp"

 8             android:layout_centerHorizontal="true" />

 9           

10        <ImageView 

11            android:layout_width="match_parent"

12            android:layout_height="match_parent"

13            android:layout_alignRight="@id/strut"

14            android:layout_alignParentLeft="true"

15            android:background="@drawable/hankukko"/>

16 

17        <ImageView 

18            android:layout_width="match_parent"

19            android:layout_height="match_parent"

20            android:layout_alignLeft="@id/strut"

21            android:layout_alignParentRight="true"

22            android:background="@drawable/chopper"/>

23     </RelativeLayout >

效果图如下:

RelativeLayout布局下实现控件平分空间

尾注:如果想要实现更加复杂的多等分,还是推荐使用LinearLayout设置权重的方法。

 

转载请注明出处:http://www.cnblogs.com/michaelwong/p/4114945.html

 

你可能感兴趣的:(RelativeLayout)