Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 介面設計:RelativeLayout 的規則、屬性與實戰範例

編輯:關於 Android 程式設計

理解版面配置是寫出好 Android 程式的基礎功課。RelativeLayout 是其中功能最強、也最容易被誤用的一個——用對了,它能以極淺的層級搭出複雜畫面;用錯了,只會掉進循環依賴的泥沼。

什麼是 RelativeLayout

除了把元件排成一列或一欄的 LinearLayout,RelativeLayout 是另一種極普及的版面型別。與其他 Layout 一樣,它可以透過 XML 資源定義,也可以用 Java 程式建立。

它的行為如其名:相對於其他元件或父容器本身來排列元件。具體來說,子元件(ImageView、TextView、Button 等)可以被放在另一個元件的上方、下方、左方或右方;也可以相對於父容器擺放,包括靠齊四邊緣,以及水平或垂直居中。

子元件的位置由「規則」定義,這些規則決定了元件在 RelativeLayout 中的呈現方式。完整清單可查 RelativeLayout 類別的 SDK 文件,對應的 XML 屬性也在其中。

一個絕對必要的條件:每個子元件都必須正確設定自己的 id,規則才有依據可循。

最簡單的範例

假設要設計一個畫面,包含一個 EditText 與一個 Button,希望 Button 顯示在 EditText 的右側。做法是定義一個 RelativeLayout,底下兩個子元件各自帶規則:EditText 對齊父容器左側、並位於 Button 左邊;Button 則對齊父容器右側。

XML 寫法如下(放在 res/layout/relative.xml):

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">

    <EditText
        android:id="@+id/EditText01"
        android:hint="Enter some text..."
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/Button01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/Button01"
        android:text="Press Here!"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content" />

</RelativeLayout>

在 Activity 的 onCreate() 中,只要一行就能載入:

setContentView(R.layout.relative);

這個版面設定了寬高皆填滿螢幕,子元件共套用三條規則:EditText01 對齊左側、EditText01 位於 Button01 左邊、Button01 對齊右側。

用程式碼建立 RelativeLayout

相對位置也能完全用 Java 描述,靠的是 RelativeLayout.LayoutParams 與 addRule():

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    EditText ed = new EditText(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params.addRule(RelativeLayout.LEFT_OF, 1001);
    ed.setLayoutParams(params);
    ed.setHint("Enter some text....");

    Button but1 = new Button(this);
    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    but1.setLayoutParams(params2);
    but1.setText("Press Here!");
    but1.setId(1001);

    RelativeLayout layout1 = new RelativeLayout(this);
    layout1.setLayoutParams(new LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    layout1.addView(ed);
    layout1.addView(but1);
    setContentView(layout1);
}

這裡有個順序陷阱值得留意:Button 必須在 EditText 引用它之前先設定好 id。程式碼中我把 but1.setId(1001) 放在設定 ed 的規則之後才執行,嚴格來說是有風險的寫法——實務上應該先給 Button 配置 id,再建立對它的引用規則,否則規則會指向一個尚無 id 的元件。

如你所見,元件一多,程式碼量膨脹得很快。因此用程式碼建立版面,最好只用於特殊情況,一般開發仍以 XML 為主。

重要的屬性分類

專屬於 RelativeLayout 的子規則大致分四類:

  • 相對於父容器居中:水平居中、垂直居中,或兩者皆居中
  • 相對於父容器排列:靠頂、靠底、靠左、靠右
  • 相對於其他元件對齊:與另一元件的頂、底、左、右緣對齊
  • 相對於其他元件擺放:置於另一元件的上、下、左、右側

此外,通用的 ViewGroup 風格屬性也適用,包括必須指定的 layout_height 與 layout_width,以及 margin_top、margin_left、margin_right、margin_bottom 等邊距設定。

進階實戰:七色方塊排版

來做一個稍複雜的練習。目標畫面用七個不同顏色的 TextView 拼出特定構圖,我們從最終效果反推規則。

步驟一:定義 RelativeLayout 因為它要掌控整個畫面,寬高都設為 fill_parent。

步驟二:放進七個 TextView 各自設定文字、背景色、字色、內距等外觀屬性。

步驟三:為每個元件定義規則

  • RED:不設任何規則。預設位置就是父容器左上角。
  • ORANGE:水平居中。由於預設靠左上角,這實際上把它放到頂邊中央。
  • YELLOW:對齊父容器右緣,形成右上角。
  • GREEN:垂直居中,且位於 BLUE 的左側。
  • BLUE:在父容器中完全居中(水平與垂直),是本組的視覺核心。
  • INDIGO:垂直居中,且位於 BLUE 的右側。
  • VIOLET:對齊父容器底緣,寬度設為填滿,延伸至螢幕下緣。

對應的 XML 片段(節錄關鍵規則):

<TextView android:id="@+id/TextView01" android:text="RED"
    android:background="#f00" android:textColor="#000"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:gravity="center" android:padding="25dp" />

<TextView android:id="@+id/TextView02" android:text="ORANGE"
    android:layout_centerHorizontal="true"
    android:background="#ffa500" />

<TextView android:id="@+id/TextView03" android:text="YELLOW"
    android:layout_alignParentRight="true"
    android:background="#ffff00" />

<TextView android:id="@+id/TextView04" android:text="GREEN"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/TextView05"
    android:background="#0f0" />

<TextView android:id="@+id/TextView05" android:text="BLUE"
    android:layout_centerInParent="true"
    android:layout_margin="10dp"
    android:background="#00f" android:textColor="#fff" />

<TextView android:id="@+id/TextView06" android:text="INDIGO"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/TextView05"
    android:background="#4b0082" android:textColor="#fff" />

<TextView android:id="@+id/TextView07" android:text="VIOLET"
    android:layout_alignParentBottom="true"
    android:layout_width="fill_parent"
    android:background="#ee82ee" />

這個範例示範了 RelativeLayout 最典型的用法:以一個居中的核心元件為錨點,讓其餘元件相對於它展開。這比用巢狀 LinearLayout 一層層包要清爽得多。

實用技巧與陷阱

id 必須唯一。規則要能正確套用,每個被引用的子元件都得有明確且唯一的 id。

小心循環依賴。當兩個元件互相指向對方時就會發生,例如 A 位於 B 左邊、同時 B 又位於 A 左邊。系統會直接拋出:

IllegalStateException: Circular dependencies cannot exist in a RelativeLayout

值得一提的是,RelativeLayout 的規則是在單一處理階段中解析的,這正是循環無法被容忍的原因。

保持規則精簡。規則越少,循環的機率越低,版面也越好維護、越有彈性。

橫直向都要測。-relative 本質上是比例導向的,同一份版面在橫屏、不同尺寸與解析度下的表現可能落差極大。上機實測無法省略。

用它取代巢狀 LinearLayout。這是最有價值的一條。多層嵌套的 LinearLayout 會讓 measure 階段重複計算,直接影響效能與回應速度。改以 RelativeLayout 扁平化,通常能明顯改善。

總結

RelativeLayout 允許子元件相對於彼此、也相對於父容器的邊緣與中心來組織。掌握規則之後,你能用相當淺的層級搭出複雜構圖,而不必過度嵌套——這既讓版面更易讀,也實際改善了效能。它是每個 Android 開發者都值得花時間弄熟的版面型別。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved