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

Android 版面排列與對齊:orientation、gravity 與 FrameLayout

編輯:關於 Android 開發

寫 Android 版面時,最常被搞混的莫過於那幾個排列與對齊屬性。它們名字相似、作用卻截然不同,一旦分不清楚,畫面就會出現「怎麼調都不對」的窘境。以下逐一釐清。

android:orientation:決定排列方向

這個屬性控制子元素的排列軸向。horizontal 讓所有子元素由左至右水平排開,vertical 則讓它們由上至下垂直堆疊。

gravity 與 layout_gravity:一組關鍵區別

兩者字面上只差一個前綴,意義卻完全不同:

  • android:gravity:指定本元素的子元素相對它自己的對齊方式。
  • android:layout_gravity:指定本元素相對它父容器的對齊方式。

換句話說,gravity 是「我怎麼擺我的小孩」,layout_gravity 是「我的父親怎麼擺我」。

看個例子。以下 LinearLayout 把 android:gravity 設為 right,於是它的兩個子元素 Button01 與 Button02 都會被推到右側:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="right">
    <Button android:text="button01" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    <Button android:text="button02" android:id="@+id/Button02"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

再來看 layout_gravity。這次父層不做任何對齊設定,改由子元素各自表明立場:Button01 靠左、Button02 靠右:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:layout_gravity="left"
        android:text="button01"
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Button>

    <Button
        android:layout_gravity="right"
        android:text="button02"
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Button>
</LinearLayout>

實務上的判斷很簡單:想讓整組子元素一起靠邊,用父層的 gravity;想讓某幾個子元素各自站位,用子層的 layout_gravity。

FrameLayout:最樸素的一塊畫布

FrameLayout 是所有版面容器中最簡單的一個。它被設計成螢幕上一塊空白的備用區域,之後你在其中放入單一物件——例如一張要展示的圖片。它所有的子元素都會被固定在左上角,你無法為 FrameLayout 中的子元素指定位置;而後加入的子元素會直接疊在前一個之上,將其部分或全部遮住(除非後者是透明的)。正因如此,它常被拿來做圖片與文字的堆疊、 Loading 遮罩,或是需要手動控制可見性的重疊場景。

幾個 FrameLayout 的 XML 屬性

先用 XML 描述界面,再由 Activity 的 setContentView() 依這份「設計圖」生成真正的控制項物件——這個分工是 Android 版面的基本模型。FrameLayout 可用的屬性來自三處:從父類繼承而來、由嵌套類別定義、以及自身定義。

android:id

這個屬性繼承自 android.view.View,為 FrameLayout 提供一個唯一識別碼。之後程式可以透過 View.findViewById() 或 Activity.findViewById() 把它找回來。

android:layout_width 與 android:layout_height

分別定義布局寬與高,取值通常是 fill_parent 或 wrap_content。前者表示在該軸向上撐滿父容器的空間,後者則表示有多少內容就取多大。這兩個屬性定義在 android.widget.FrameLayout.LayoutParams 這個嵌套類別之中。

android:background 與 android:foreground

顧名思義,分別是背景與前景。FrameLayout 因為子元素會互相遮疊,前景屬性特別好用——例如想在所有內容之上蓋一層半透明遮罩或邊框,用 foreground 會比多加一層子 View 更乾淨。

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