天天看點

【android-tips】android xml布局總結篇一.背景二基礎知識

        可能很多人跟我一樣,做了好久的android程式,卻一直沒有認真地坐下來好好學習下xml檔案的布局。其實有的時候我們用view繪制或是利用ADT的圖形界面功能就可以輕松搞定布局,但是最好還是靜下來學習下xml的布局檔案具體寫法。這一節我們要繪制如下圖所示的界面。

【android-tips】android xml布局總結篇一.背景二基礎知識

       首先我們要了解android到底有那些布局,和每個布局類型的差別。

         線性布局分兩種。一種是水準布局,一種是垂直布局。下面我們根據上圖舉例子。

         先把上圖的代碼貼出來吧!

android:orientation="horizontal"

>

<ImageButton android:id="@+id/ImageButton01"

android:layout_width="72dp" android:layout_height="72dp"

android:src="@drawable/sketchy_paper_003" android:layout_margin="3dp"></ImageButton>

<ImageButton android:id="@+id/ImageButton02"

android:src="@drawable/sketchy_paper_004" android:layout_margin="3dp"></ImageButton>

<ImageButton android:id="@+id/ImageButton03"

android:src="@drawable/sketchy_paper_007" android:layout_margin="3dp"></ImageButton>

<ImageButton android:id="@+id/ImageButton04"

android:src="@drawable/sketchy_paper_011" android:layout_margin="3dp"></ImageButton>

</LinearLayout>

可以看到,上圖是由三部分組成。在大的LinearLayout從上而下垂直分布着三個内容:TextView,LinearLayout,LinearLayout。是以總體的LinearLayout是垂直布局

下面我們來看水準布局

其實就是上圖中的最下面那個LinearLayout。四個圖示平行排列。

這個布局相對簡單一點。一般來講利用ADT自己拖放按鈕就可以。基本上可以随意布局。如下圖所示

【android-tips】android xml布局總結篇一.背景二基礎知識

代碼是

下面這兩句是居左顯示和居右顯示

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

常用語句總結:

 android:layout_toLeftOf

—— 該元件位于引用元件的左方

    android:layout_toRightOf

—— 該元件位于引用元件的右方

    android:layout_above

—— 該元件位于引用元件的上方

    android:layout_below

—— 該元件位于引用元件的下方

   android:layout_alignParentLeft —— 該元件是否對齊父元件的左端

   android:layout_alignParentRight —— 該元件是否齊其父元件的右端

   android:layout_alignParentTop —— 該元件是否對齊父元件的頂部

   android:layout_alignParentBottom —— 該元件是否對齊父元件的底部

    android:layout_centerInParent

—— 該元件是否相對于父元件居中

 

   

android:layout_centerHorizontal —— 該元件是否橫向居中

  android:layout_centerVertical

—— 該元件是否垂直居中

總之,相對視圖應該是最有用的,具體的操作比較複雜,更多的是通過圖形界面拖拉,再用代碼微調!

這個布局很簡單,而且感覺有點二二的,哈哈!就是控件一個挨一個在左上角羅列。

【android-tips】android xml布局總結篇一.背景二基礎知識

代碼

絕對布局比較容易使用,就是以左上方為原點建立坐标系。每個控件用layout_x和layout_y表示位置。但是據說這種布局比較剛性,不容易适配各種終端,是以要慎用!

【android-tips】android xml布局總結篇一.背景二基礎知識

TableLayout有點像一個表格或是矩陣。在布局中加入TableRow,它的屬性是horizontal是以每個TableRow隻能橫放。它裡面的每個控件的高都是一樣的。下圖所示,是加入了一個TableRow和裡面的控件。

【android-tips】android xml布局總結篇一.背景二基礎知識

ok!你學會了麼,have fun!

繼續閱讀