Linear Layout(線形佈局)

線性佈局

LinearLayout 是一種會把所有的子元素排列成一個方向(水平或垂直)的ViewGroup。你可以使用 android:orientation 屬性來指定佈局的方向。

LinearLayout 的所有子元素都是一個挨着一個排列的,所以對於垂直的列表來說不管子元素有多寬每行只會有一個子元素,水平的列表只會有一行高(最高子節點的高度加上內邊距)。LinearLayout 涉及到子元素間的外邊距和每個子元素的重心(左、中或右對齊)。

佈局比重


相同比重的子元素

把每個子視圖的 android:layout_height 設置爲"0dp"(對於對平佈局)或把每個子視圖的 android:layout_width 設置爲"0dp"(對於垂直佈局),然後把每個視圖的 android:layout_weight 設置爲"1",這樣就能創建一個每個子元素在屏幕上佔據相同大小空間的線性佈局。

LinearLayout 也支持使用 android:layout_weight 屬性爲單個的子元素指定比重。視圖會依照這個屬性指定的值來決定應該佔用屏幕多大空間。大的比重值可以使視圖擴展來填充父元素視圖中所有剩餘的空間。子元素視圖指定比重值後,ViewGroup中的所有剩餘空間會依照他們聲明的比例指定給子元素。默認比重值是0。

例如,如果有三個文本框,其中兩個的比重值是1,另外一個沒有指定比重值,那麼沒有比重值的文本框只會佔用它的內容需要的區域,另外兩個會在三個文本被框測量後平均佔用剩餘的空間。如果第三個文本框的比重被設置爲2(而不是0),那麼它現在被聲明的比其他兩個重要了,所以它會擁有總空間的一半,第一和第二個文本框平分剩餘的。

事例


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/subject" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="@string/message" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="@string/send" />
</LinearLayout>

請查閱 LinearLayout.LayoutParams 瞭解更多關於 LinearLayout 中子元素視圖可用屬性的細節。

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