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

用 XML 寫 Android 介面:宣告式布局的優勢與實作

編輯:進階開發

上一篇我們談完了 ListView 的資料綁定,接下來換個角度,看看 Android 另一套同樣屬於「可視化編程」的 approach——用 XML 描述介面。

為什麼 Android 選擇 XML 來存介面

如同許多跨平台的 UI 函式庫,Android 也以 XML 檔案來描述畫面上的元件與它們的相對位置。目前主流的行動介面框架幾乎都走這條路,原因很單純:把「長什麼樣子」與「做了什麼事」分開,兩邊都能各自獨立演進。

在專案中,res/layout/ 目錄下會有一個或多個 .xml 檔,每一個就是一個畫面的布局描述。打開 res/layout/main.xml:

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:id="@+id/mainView" />
</LinearLayout>

這份布局用一個 LinearLayout 作為容器,裡面擺一個 TextView,也就是一個 View。Activity 要在 onCreate() 中一行搞定載入:

this.setContentView(R.layout.main);

其中 R.layout.main 是編譯環境自動產生的索引值,指向 res/layout/main.xml。

setContentView 的一句話,等同於這一串程式

很多人第一次看到 XML 會懷疑:這行呼叫背後到底做了什麼?答案其實很樸素——它等價於你用純程式碼手動組出同一棵元件樹:

LinearLayout layout = new LinearLayout(this);
TextView tv = new TextView(this);
tv.setText(R.string.hello);
layout.addView(tv);
this.setContentView(layout);

兩者最終都交出一個根 View 給 Activity。差別在於可讀性與維護成本:XML 版本一眼就能看出結構層級,程式碼版本則在元件數量增加後迅速變得難以閱讀。

至於 R.string.hello 同樣是資源映射的 ID,它會去讀取 res/values/strings.xml 中 name 為 hello 的那筆值。理解了「XML 描述結構、R 類索引資源」這兩個概念,Android 的介面開發就沒有太多黑箱了。

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