安卓的佈局分為5大類,FrameLayout(框架佈局),LinearLayout (線性佈局),AbsoluteLayout(絕對佈局),RelativeLayout(相對佈局)和TableLayout(表格佈局)。每種佈局都有自己佈局的特點和不同的應用場合
,各種標簽之間可以嵌套。
FrameLayout是最簡單的一個佈局對象。它被定制為你屏幕上的一個空白備用區域,之後你可以在其中填充一個單一對象;
LinearLayout以你為它設置的垂直或水平的屬性值,來排列所有的子元素。水平和豎直排列的方式在XML中用android:orientation="vertical" 和android:orientation="horizontal"來定義;所有的子元素都被堆放在其它元素之後,因此一個垂直列表的每一行隻會有 一個元素,而不管他們有多寬,而一個水平列表將會隻有一個行高(高度為最高子元素的高度加上邊框高度)。LinearLayout還支持為單獨的子元素指定weight,例如android:layout_weight="1",其好處就是允許子元素可以填充屏幕上的剩餘空間。這也避免瞭在一個大屏幕中,一串小對象擠 成一堆的情況,而是允許他們放大填充空白。子元素指定一個weight 值,剩餘的空間就會按這些子元素指定的weight 比例分配給這些子元素。默認的 weight 值為0。例如,如果有三個文本框,其中兩個指定瞭weight 值為1,那麼,這兩個文本框將等比例地放大,並填滿剩餘的空間,而第三個文本框不會放大。 AbsoluteLayout 可以讓子元素指定準確的x/y坐標值,並顯示在屏幕上。AbsoluteLayout 沒有頁邊框,允許元素之間互相重疊(盡管不推薦)。因為它使界面代碼太過剛性,以至於在不同的設備上可能不能很好地工作。例如:
<span style="font-family:Microsoft YaHei; font-size:14px"><span style="white-space:pre"> </span>android:layout_x="250px" //設置按鈕的X坐標 android:layout_y="40px" //設置按鈕的Y坐標 android:layout_width="70px" //設置按鈕的寬度</span>
RelativeLayout 允許子元素指定他們相對於其它元素或父元素的位置(通過ID 指定)。因此,你可以以右對齊,或上下,或置於屏幕中央的形式來 排列兩個元素。貌似是現在默認的佈局方式來著,所以應該使用比較普遍一些。
<span style="font-family:Microsoft YaHei; font-size:14px"><RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:text="button" /> </RelativeLayout></span>
TableLayout 將子元素的位置分配到行或列中。一個TableLayout 由許多的TableRow 組成,每個TableRow都會定義一個 row 。
除瞭在activity_main.XML這個文件中用XML語言定義元素的佈局之外,還可以在Graphical Layout裡面用可視化的頁面拖拽去進行佈局或者是在文件裡用java進行編寫。