Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

關於 Android RelativeLayout 的一些看法

編輯:Android 開發實例

先交代一下背景:以前很少使用 RelativeLayout,這次專案剛好用到,實際上手後才發現它實在太過靈活,而這種靈活也很容易讓人誤入陷阱。以下分享我的一些看法。

官方 Tutorials 提到:如果發現自己使用了大量巢狀的 LinearLayout 群組,或許可以用單一 RelativeLayout 來取代它們。我的理解是,官方之所以這樣建議,某種程度正是因為 RelativeLayout 太過靈活,而過度的靈活反而會對我們控制 UI 造成一定影響,因此才會提醒「當有多層 ViewGroup 巢狀時再考慮改用 RelativeLayout」。

曾經有人對我說,RelativeLayout 與 FrameLayout 有幾分相似,都帶有「分層」的感覺、有層次的概念。但我認為並非如此——RelativeLayout 並沒有「層」的概念,從官方解釋來看,它只是一個能設定相對位置關係的布局而已。

先來看一段程式碼,會更直觀:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#CCFFFF">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:background="#32000033"
        android:orientation="vertical">
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#FF3300"
            android:text="Button" />
        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Base"
            android:textColor="#6633FF"
            android:gravity="center" />
        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#FF3300"
            android:text="Button" />
    </LinearLayout>

    <Button
        android:id="@+id/button3"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:layout_alignBottom="@id/linearLayout"
        android:text="button" />
</RelativeLayout>

Activity 沒有什麼特別,只是單純把這個布局顯示出來。執行後可以明顯看到,button3 的下緣正好與 linearLayout 的下緣落在同一條水平線上。

然而,若把屬性改成 android:layout_alignBottom="@id/button1",我們可能期望 button3 的下緣能與 button1 的下緣對齊,但實際執行卻不是這麼一回事——這樣寫根本不會生效。

其中的原因,我是這樣理解的:首先,linearLayout、Button 這些元件都同屬 android.widget 套件,彼此是同一個層級的,只是 linearLayout 身為一個 ViewGroup,可以再容納其他 View 而已,它們之間並不存在其他的優先順序關係。

因此,我的理解是:如果 button3 要與其他元件產生相對位置關係,前提是它們必須位於「同一個層級」。這裡所說的層級並不是指元件本身的類別,而是指在 XML 檔案中的配置層級——例如 linearLayout 與 button3 同為第一層,那麼被 linearLayout 包住的 button1、textView、button2 就屬於第二層。只有位於同一層級的元件之間,才能設定相對位置關係,否則無論怎麼設定都不會起作用。

這就是我的理解:RelativeLayout 裡根本不存在「層」的概念。

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