2012-03-15

Android 的 xml 檔案 (二) main.xml

上次談了 strings.xml 檔案, 這次我來談談 main.xml 檔案.
main.xml 檔的作用就是用來設計畫面的格局; 有的人稱其為 [佈局檔], 預設是 main.xml, 如果你的應用程式要呈現一個以上的佈局畫面 (切換不同的畫面), 那麼你也可以設計多個佈局檔, 並且在一個 Activity 中輪番使用, 但是名稱不可相同, 例如 main.xml, main2.xml ... 至於何時該呈現哪個佈局畫面, 則必須透過程式來控制, 例如 :
if (條件)  setContentView(main.xml)  else  setContentView(main2.xml)

不過, 要想這麼做的話, 不如多創建一個 Activity 還來得比較實際些, 一個 Activity 控制一個佈局檔才不會把問題越搞越複雜.


main.xml 是否需要手動編寫 ?
在 Android 開發工具中提供了 Graphical Layout 功能, 讓開發者可以很方便地以拖曳元件的方式來佈置顯示畫面, 如下圖所示 :

Graphical Layout 設計視窗

在 Graphical Layout 設計視窗中, 可從左側的工具箱中將元件拖曳到畫面顯示區, 下方的 Properties 欄位還可以設定該元件的各項屬性, 這種直覺的設計方式為設計者省下不少寶貴的時間.

如下圖 :
我放置了一個 Button, 一個 TextView 及 一個 RatingBar, 共三個元件, 當你拖曳元件到顯示區後 (或刪除元件), 其對應的 xml 檔中 (此例為 main.xml) 亦會同步自動產生此畫面佈局的語法內容.


我們再從 Graphical Layout 視窗切換到 main.xml 視窗來看一下 xml 檔的對應內容, 天哪 ! 才放了三個元件而已, xml 檔的內容竟然那麼多 !

============================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:baselineAligned= "false"
android:layout_height="wrap_content"
android:orientation= "vertical" android:layout_width="fill_parent">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:baselineAligned="true">
        <Button android:id="@+id/button2" android:layout_height="wrap_content"
android:text="Button" android:layout_width="wrap_content" android:layout_gravity="right"> </Button>
        <TextView android:id="@+id/textView2" android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content" android:textSize="30sp" android:layout_gravity="top"> </TextView>
    </LinearLayout>
    <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content"
android:layout_height="wrap_content"> </RatingBar>
</LinearLayout>
=============================================

如果沒有 Graphical Layout 的協助, 光是徒手編寫這些內容就夠累人的了 ! 更不用說還要撰寫後續的程式碼來控制這些元件. 不過呢 ~ 也不要太依賴 Graphical Layout 的功能喔.

有幾次我在設計時不小心按錯幾個功能項, 畫面中的元件位置因此大亂 ~ 不管怎麼調整還是調不回來, 有時是越調越亂 ! 遇到這種情形時, 我會切換到 xml 檔中直接去修改出問題的地方; 所以 ~ 先把 Graphical Layout 功能當做輔助工具, 必要時再直接去修改 xml 檔的內容會是比較好的做法 !

上述只是我的經驗分享, 如果你已經建立好你的工作方式, 請依照你原先的習慣就好 .^__^.

#本文僅就 xml 檔的概念來闡述, 其他細節請自行參考相關書籍.

沒有留言:

張貼留言

搜尋此網誌