星期五, 9月 23, 2011

Layout

Android應用程式學習筆記

Layout

要定義布局與表示視圖階層的最普遍的方式就是xml的布局文件,XML為布局提供一個我們較好閱讀的結構,XML很像HTML。在XML裡的標籤不是View物件就是ViewGruop物件,View物件視階層樹的葉子,ViewGroup物件視階層樹的枝幹。

XML標籤的名字各自以Java類別的顯示。所以在你的UI中,一個<TextView>標籤產生一個TextView,而一個<LinearLayout>標籤產生一個LinearLayout的ViewGroup。當你裝載一個布局資源,android系統就會初始這些物件,對應你布局文件的標籤。

以下有一個例子,簡單的垂直布局有一個textview及一個按鈕:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>

注意到LinearLayout標籤中容納了TextView與Button,你可以巢狀增加其他LinearLayout在這裡面,去延長視圖階層樹並產生更複雜的布局。

沒有留言:

張貼留言