LinearLayout
是檢視區塊群組,可讓所有子項依單一方向 (垂直或水平) 對齊。您可以使用 android:orientation
屬性指定版面配置方向。
![顯示版面配置分割為三個垂直切片的圖片](https://developer.android.com/static/images/ui/linearlayout.png?authuser=7&hl=zh-tw)
LinearLayout
。LinearLayout
的所有子項會依序堆疊,因此無論寬度為何,垂直清單的每一列都只有一個子項。水平清單只有一列高,也是最高子項的高度,再加上邊框間距。LinearLayout
會遵循子項之間的「邊界」,以及每個子項的「重力」(靠右、置中或靠左對齊)。
版面配置權重
LinearLayout
也支援使用 android:layout_weight
屬性,將「權重」指派給個別子項。這項屬性會根據其在畫面上所佔的空間,將「重要性」值指派給檢視畫面。較大的權重值可讓其展開以填滿父項檢視區塊中的剩餘空間。子檢視畫面可以指定權重值,而檢視區塊群組中的剩餘空間會根據宣告的權重,按比例指派給子項。預設權重為 0。
均等分布
如要建立線性版面配置,並讓每個子項在螢幕上使用相同大小的空間,請將每個檢視畫面的 android:layout_height
設為 "0dp"
,或是將每個檢視畫面的 android:layout_width
設為 "0dp"
進行水平版面配置。然後將每個檢視畫面的 android:layout_weight
設為 "1"
。
不等分布
您還可以建立線性版面配置,讓子元素在畫面上使用不同大小的空間。請見以下範例:
- 假設您有三個文字欄位,其中兩個文字欄位的權重值為 1,第三個文字欄位的預設權重值為 0。第三個文字欄位 (權重值為 0) 僅佔用其內容所需的區域。另外兩個文字欄位 (權重值為 1) 會均等展開,以在測量所有三個欄位的內容後剩餘的空間。
- 相反地,如果您有三個文字欄位,其中兩個的權重值為 1,第三個欄位的權重為 2,則系統會按照以下方式分配在全部三個欄位內容後方保留的空間:權重值為 2 的欄位減半至權重值 2 的欄位之間,一半則平均分配給權重值為 1 的欄位。
下圖和程式碼片段顯示版面配置權重在「傳送訊息」活動中的運作方式。「To」(收件者) 欄位、「Subject」(主旨) 行和「Send」(傳送) 按鈕只佔用所需的高度。訊息區域會佔據活動的其餘高度。
![顯示三個 EditText 和一個垂直方向的 LinearLayout 按鈕的圖片](https://developer.android.com/static/images/ui/sample-linearlayout.png?authuser=7&hl=zh-tw)
LinearLayout
的三個文字欄位和按鈕。<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/to" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/subject" /> <EditText android:layout_width="match_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="end" android:text="@string/send" /> </LinearLayout>
如要進一步瞭解 LinearLayout
每個子檢視畫面可用的屬性,請參閱 LinearLayout.LayoutParams
。