android相對佈局

Activity佈局初步 - 相對佈局 
1、 相對佈局的基本概念 
一個控件的位置它決定於它和其他控件的關係,好處:比較靈活;缺點:掌握比較複雜。 
2、 相對佈局常用屬性介紹 
這裏將這些屬性分成4個組,便於理解和記憶。 
a)、以下4個屬性設置控件與之間的關係和位置 



但是上面4個屬性並沒有設置各個控件之間是否對齊。 
示例1:將控件A放置在控件B的上面,則使用android:layout_above屬性,控件佈局的效果可以有以下這麼兩種情況。 
1、 控件A與控件B對齊,並且控件A是在控件B的上面。 
2、 控件A沒有與控件B對齊,但是控件A又確實是在控件B的上面。 

 



b)、以下5個屬性,設置的是控件與控件之間對齊的方式(是頂部、底部還是左、右對齊)。 



示例2:在示例1的基礎上,設置控件A放置在控件B的上面,使用android:layout_above屬性,並且控件A的左邊邊緣與控件B的左邊邊緣對齊,使用android:layout_alignLeft屬性。 



c)、以下4個屬性設置控件與父控件之間對齊的方式(是頂部、底部還是左、右對齊)。 



d)、以下4個屬性設置控件的方向。 



可以通過組合這些屬性來實現各種各樣的佈局。 
注:以上屬性和其他更多屬性的作用都能在android的幫助文檔中找到; 

示例3:假如要實現一個如下圖這樣佈局的程序 


如果這樣的佈局要使用LinearLayout的話會比較麻煩和複雜, 
1、 首先需要一個垂直佈局方向的LinearLayout,包裹所有的控件; 
2、 然後在第一個LinearLayout中嵌套一個垂直方向的LinearLayout,放在上部分,在這個LinearLayout中放入一個TextView和EditText; 
3、 最後還是在第一個LinearLayout中嵌套一個水平方向的LinearLayout,放在第一個LinearLayout的下部分,在這個LinearLayout中放入兩個Button,並且還得讓它們居右。 
可參考下圖: 



如果使用RelativeLayout會要簡單很多,下面爲main.xml的代碼。 

Java代碼 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="wrap_content"  
  6.     android:padding="10px"  
  7.     >  
  8.     <TextView  
  9.         android:id="@+id/lable"  
  10.         android:text="Type here:"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.     />  
  14.       
  15.     <EditText  
  16.         android:id="@+id/entry"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:background="@android:drawable/editbox_background"  
  20.         android:layout_below="@id/lable"  
  21.     />  
  22.       
  23.     <Button  
  24.         android:id="@+id/ok"  
  25.         android:layout_width="wrap_content"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="OK"  
  28.         android:layout_below="@id/entry"  
  29.         android:layout_marginLeft="10px"  
  30.         android:layout_alignParentRight="true"  
  31.     />  
  32.       
  33.     <Button  
  34.         android:id="@+id/cancel"  
  35.         android:layout_width="wrap_content"  
  36.         android:layout_height="wrap_content"  
  37.         android:layout_toLeftOf="@id/ok"  
  38.         android:layout_alignTop="@id/ok"  
  39.         android:text="Cancel"  
  40.     />  
  41. </RelativeLayout>  

Android技術交流QQ羣:141188656       歡迎加入

發佈了72 篇原創文章 · 獲贊 13 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章