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

Android 佈局詳解:FrameLayout frame 佈局的堆疊原理與前景屬性

編輯:關於 Android 開發

FrameLayout 是什麼

Frame 這個名字來自「幀」,也就是動畫裡的一格畫面。FrameLayout 為加入其中的每個子元件配置一個空白區域,這些區域彼此重疊在同一個位置上,因此它本質上是一個「層疊容器」:後加入的元件會蓋在先加入的元件上面。

每個子元件在這一幀裡的落點,由 layout_gravity 決定,可以置中、靠左上、靠右下等等。

兩個專屬屬性

  • foreground:設定 frame 的前景圖像,它會畫在所有子元件之上,常用來做遮罩、邊框或漸層效果。
  • foregroundGravity:控制這張前景圖的對齊方式,例如 top|left、center。

實作範例:三層方塊的視覺堆疊

下面的例子放入三個尺寸遞減的 TextView,全部置中,於是形成由紅、綠、藍三色構成的同心方塊。

<?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">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:width="300dp"
            android:height="300dp"
            android:background="#f00" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:width="200dp"
            android:height="200dp"
            android:background="#0f0" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:width="100dp"
            android:height="100dp"
            android:background="#00f" />
    </FrameLayout>
</LinearLayout>

實務上的常見用途

FrameLayout 最適合「單一位置、多層內容」的情境:比如在圖片上方疊一層載入中的轉圈動畫、在清單項右下角疊一個未讀紅點、在播放器畫面上疊控制列與浮水印。它也正是 TabHost、ViewPager 這類需要「一次只呈現一頁」的元件背後所使用的容器。

需要留意的是,由於所有子元件都佔用同一塊區域,FrameLayout 本身不提供任何排列能力;一旦你的需求是「並排」或「間隔」,就該換成 LinearLayout 或 RelativeLayout。

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