使用者介面是人与手機溝通的橋樑,也是使用者對一個 App 的第一印象。Android 的 UI 由 View 與 ViewGroup 兩類物件構成,兩者都是 View 的子公司別。
顧名思義就是「線性配置」:標籤底下所有子元素會依 android:orientation 的值,逐個沿著水平或垂直方向排成一列。
它最大的特性是簡單,最大的限制也是簡單——只能排一條線。想做上下兩列、每列內部又是左右並排的表單,就必須靠嵌套:外層垂直、內層水平。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 第一列:帳號 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<!-- 第二列:密碼 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/userpass" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<!-- 第三列:按鈕群,用 TableLayout 橫向並排 -->
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel" />
</TableRow>
</TableLayout>
</LinearLayout>
orientation="vertical" 決定三個區塊上下堆疊;兩個內層 LinearLayout 用 horizontal 讓文字標籤與輸入框左右並排。這就是嵌套的價值。wrap_content、輸入框用 fill_parent(新版建議寫 match_parent),是表單類版面的標準搭配,能讓輸入框吃滿該列剩餘空間。res/values/strings.xml,方便日後多語系與重複使用。