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

Android 入門:LinearLayout 與 AbsoluteLayout 用法實例講解

編輯:關於 Android 程式設計

本文以實例介紹 Android 的 LinearLayout 與 AbsoluteLayout,希望對剛入門的朋友有些幫助。

Android 的 UI 佈局都以 Layout 作為容器,控件在其中按規則排列,這點和 Java 的 Swing、LWUIT 頗為相似。控件與 Layout 有大量共同屬性,可以直接在 Properties 面板中修改,開發體驗近似 .NET/Delphi 這類 RAD 工具。以下是最常用的幾項:

id="@+id/edtInput"——id 是連接 UI 與程式碼的橋梁。

gravity="center"——讓 Layout 中的控件置中:

layout_width="fill_parent"——自動填滿螢幕寬度,layout_height 同理:

layout_width="wrap_content"——自動收縮為控件本身的大小,layout_height 同理:

LinearLayout——前面實例所用的就是它,概念很簡單:其中的控件按水平或垂直方向排列。orientation="horizontal" 是水平排列,orientation="vertical" 是垂直排列。這裡有個常見的坑:當 LinearLayout 是 horizontal,而裡面的控件又設了 layout_width="fill_parent",那麼後續的控件會被擠到螢幕右側之外,直接看不見了。

AbsoluteLayout——顧名思義,用絕對座標定位控件。正因為寫死了座標,一旦螢幕尺寸或解析度變化,介面就容易走形,所以要做自適應佈局時應盡量避免它。其中的控件以 layout_x、layout_y 決定位置:

 

上圖中 TextView01 的 X 座標為 110px、Y 座標為 10px,佈局程式碼如下:

 <AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_height="wrap_content" android:layout_width="fill_parent" > <TextView android:text="TextView01" android:id="@+id/TextView01" android:layout_height="wrap_content" android:layout_y="10px" android:layout_width="wrap_content" android:layout_x="110px"> </TextView> </AbsoluteLayout>

實務上的結論很明確:能自適應的場合用 LinearLayout 搭配 weight,需要疊放時用 RelativeLayout 或 FrameLayout,AbsoluteLayout 只適合那些螢幕尺寸完全固定的特殊場景。

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