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 >

效果圖如下:

再次來實現垂直等分,原理與水平相似,只是修改方位。

關鍵代碼如下:

 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 >

效果圖如下:


尾注:如果想要實現更加復雜的多等分,還是推薦使用LinearLayout設置權重的方法。

 

轉載請注明出處:http://www.cnblogs.com/michaelwong/p/4114945.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM