線性布局
阿新 • • 發佈:2017-06-24
空間 文本 技術分享 其中 amp att viewgroup htm attr 均設置為
LinearLayout
是一個視圖組,用於使所有子視圖在單個方向(垂直或水平)保持對齊。 您可以使用 android:orientation
屬性指定布局方向。
LinearLayout
的所有子視圖依次堆疊,因此無論子視圖有多寬,垂直列表每行均只有一個子視圖,水平列表將只有一行高(最高子視圖的高度加上內邊距)。 LinearLayout
遵守子視圖之間的“邊距”以及每個子視圖的“重力”(右對齊、居中對齊、左對齊)。
布局權重
權重相等的子視圖
要創建一個線性布局,讓每個子視圖在屏幕上都占據相同的空間量,則將每個視圖的 android:layout_height
均設置為 "0dp"
(對於垂直布局),或將每個視圖的android:layout_width
"0dp"
(對於水平布局)。 然後,將每個視圖的 android:layout_weight
均設置為 "1"
。
LinearLayout
還支持使用 android:layout_weight
屬性為各個子視圖分配權重。此屬性根據視圖應在屏幕上占據的空間量向視圖分配“重要性”值。 權重值更大的視圖可以填充父視圖中任何剩余的空間。子視圖可以指定權重值,然後系統會按照子視圖聲明的權重值的比例,將視圖組中的任何剩余空間分配給子視圖。 默認權重為零。
例如,如果有三個文本字段,其中兩個聲明權重為 1,另一個沒有賦予權重,則沒有權重的第三個文本字段將不會擴展,並且僅占據其內容所需的區域。 另外兩個文本字段將以同等幅度進行擴展,以填充所有三個字段都測量後還剩余的空間。 如果為第三個字段提供權重 2(而非 0),那麽相當於聲明現在它比其他兩個字段更為重要,因此,它將獲得總剩余空間的一半,其他兩個均享余下空間。
示例
<?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
。
線性布局