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

打造簡潔的 Android 使用者介面:從 LinearLayout 說起

編輯:關於 Android 程式設計

Android 應用的圖形介面由 View 與 ViewGroup 物件組成的階層結構建構而成。View 通常是按鈕、文字欄等 UI 元件,而 ViewGroup 則是定義子元件排列方式的不可見容器,例如網格或縱向清單。Android 提供對應的 XML 詞彙,讓你能用 XML 定義介面的元素階層。

用 XML 而非執行期程式碼宣告版面有個重要好處:能為不同螢幕尺寸建立各自的版面配置。

建立 LinearLayout

開啟 res/layout/ 下的 activity_main.xml,先刪除 <TextView> 元素,並將 <RelativeLayout> 改為 <LinearLayout>,再加入 android:orientation 並設為 "horizontal":

<?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"
android:orientation="horizontal" >
</LinearLayout>

LinearLayout 會依 android:orientation 屬性以垂直或水平方式排列子元件,每個子元件依 XML 中的順序呈現。作為根視圖,它將寬高設為 "match_parent" 以填滿整個可用區域。

加入文字欄位

在 <LinearLayout> 中加入 <EditText> 以建立可編輯的文字欄:

<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />

關於這些屬性:android:id 提供元件的唯一識別碼,讓你能在程式碼中參照它;@ 符號在 XML 中參照任何資源時都必須使用,而 + 符號僅在第一次定義資源 ID 時需要。android:layout_width 與 height 使用 "wrap_content" 表示僅佔據容納內容所需的大小。android:hint 則是文字欄為空時顯示的預設字串。

加入字串資源

介面中的文字應一律以資源形式指定,便於集中管理與多語言本地化。開啟 res/values/strings.xml,刪除名為 "hello_world" 的元素,新增 "edit_message" 並設值為 "Enter a message",同時為按鈕加入 "button_send":

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>

加入按鈕

緊接著 <EditText> 加入 <Button>:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />

讓輸入框填滿螢幕寬度

目前 EditText 與 Button 都只佔內容所需大小。對按鈕來說沒問題,但文字欄可能輸入較長內容,因此最好用 weight 屬性讓它填滿剩餘寬度。weight 是相對權重值,例如一個 view 權重為 2、另一個為 1,總和為 3,則前者佔 2/3、後者佔 1/3。所有 view 的預設 weight 為 0,因此只要給 EditText 一個大於 0 的值,它就會填滿其餘空間:

<EditText
android:layout_weight="1"
android:layout_width="0dp"
... />

使用 weight 時,建議把 EditText 的寬度設為 0dp 以提升效能,因為 "wrap_content" 會需要先計算一個最終無用的寬度,反而多餘。

完整的版面配置檔如下:

<?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"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>

在 Eclipse 中點選 Run,或於命令列執行 ant debug 再透過 adb install 安裝,即可看到成果。

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