線性版面配置

LinearLayout 是檢視區塊群組,可將所有子項依同一個方向 (垂直或水平) 對齊。您可以使用 android:orientation 屬性來指定版面配置方向。

注意事項:為了獲得更佳效能和更完善的工具支援,請改為使用 ConstraintLayout 建立版面配置

所有 LinearLayout 的子項會依序堆疊,因此無論寬度為何,垂直清單的每一列都只有一個子項,而水平清單都只有一列高 (最高子項的高度加上邊框間距)。LinearLayout 會遵循子項之間的「邊界」(靠右、置中或靠左對齊) 和各子項的「重力」

版面配置權重

LinearLayout 也支援使用 android:layout_weight 屬性,將「權重」指派給個別子項。這項屬性會將「重要性」值指派給檢視畫面,以反映應在整個畫面佔多少空間。較大的權杖值可讓檢視畫面展開,以填滿父檢視模式中的任何剩餘空間。子檢視畫面可指定權重值,而檢視區塊群組中的任何剩餘空間則會按照宣告的權重比例指派給子項。預設權重為零。

均等分布

如要建立線性版面配置,讓每個子項在畫面上使用相同空間,請將每個檢視畫面的 android:layout_height 設定為 "0dp" (針對垂直版面配置),或將每個檢視畫面的 android:layout_width 設定為 "0dp" (針對水平版面配置)。接著,請將各檢視畫面的 android:layout_weight 設定為 "1"

不等分布

您還可以建立線性版面配置,讓子元素在畫面上使用不同大小的空間:

  • 如果有三個文字欄位,且其中兩個宣告的權重為 1,而另一個沒有權重,則第三個沒有權重的文字欄位不會擴大,而只會佔用其內容所需的區域。另外兩個文字欄位在測量所有三個欄位後,會均等展開以填滿剩餘的空間。
  • 如果有三個文字欄位,且其中兩個欄位宣告的權重為 1,第三個欄位的權重為 2 (而非 0),則該欄位相較於另兩個欄位更重要,因此會佔用剩餘總空間的一半,而前兩個欄位均分其餘空間。

下列程式碼片段顯示了版面配置權重在「傳送訊息」活動中的運作方式。「To」(收件者) 欄位、「Subject」(主旨) 行和「Send」(傳送) 按鈕只佔用所需的高度。這項設定可讓訊息本身佔用活動的其餘高度。

<?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="right"
        android:text="@string/send" />
</LinearLayout>

如要進一步瞭解 LinearLayout 每個子檢視畫面可用的屬性,請參閱 LinearLayout.LayoutParams