android之layout(一) FrameLayout、LinearLayout

新知識介紹:

layout:佈局。我們有很多控件,但是我們要把這些控件如何擺放,怎麼樣擺放合理、美觀,這就是佈局了。

有以下幾種佈局方式:FrameLayoutLinearLayout RelativeLayout TableLayout 。

 

現在我們來介紹前兩種:

1、FrameLayout:是 最簡單的一個佈局對象。它被定製爲你屏幕上的一個空白備用區域,之後你可以在其中填充一個單一對象 — 比如,一張你要發佈的圖片。所有的子元素將會固定 在屏幕的左上角;你不能爲FrameLayout中的一個子元素指定一個位置。後一個子元素將會直接在前一個子元素之上進行覆蓋填充,把它們部份或全部擋 住(除非後一個子元素是透明的)。

FrameLayout默認填充widget等在左上角,然後後面的控件遮住前面的,比如說有兩個TextView,Text內容分別是I am textview 1 和I am textview 2 看到的效果會如下(只顯示最新的):

 

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
xmlns:android="htHTMLtp://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="I am textview 1"
    />
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="I am textview 2"
    />
    
</FrameLayout>
 

 

這個佈局並不常用,大家可以看看就行了。

 

1、LinearLayout單向佈局,最常見的佈局,可以有橫向或者縱向佈局。所有的子元素都被堆放在其它元素之後,因此一個垂直列表的每一行只會有一個元素,而不管他們有多 寬,而一個水平列表將會只有一個行高(高度爲最高子元素的高度加上邊框高度)。LinearLayout保持子元素之間的間隔以及互相對齊(相對一個元素 的右對齊、中間對齊或者左對齊)。 

 

LinearLayout 還支持爲單獨的子元素指定weight。好處就是允許子元素可以填充屏幕上的剩餘空間。這也避免了在一個大屏幕中,一串小對象擠成一堆的情況,而是允許他們放大填充空白。子元素指定一個weight值,剩餘的空間就會按這些子元素指定的weight比例分配給這些子元素。默認的weight值爲0。例如,如 果有三個文本框,其中兩個指定了weight值爲1,那麼,這兩個文本框將等比例地放大,並填滿剩餘的空間,而第三個文本框不會放大。

 

LinearLayout是Android sdk創建project時的默認Layout,支持兩種方式,默認是垂直vertical的線性layout,另一個是水平horizontal方向的線性排列。

 

話不多說,看代碼:

這個是橫向排列,"vertical":

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://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="I am textview 1"
    />
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="I am textview 2"
    />
    
</LinearLayout>
 

 

 

這個是縱向排列,"horizontal":

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="10px" 
    android:layout_height="fill_parent" 
    android:text="I am textview 1"
    />
    <TextView  
    android:layout_width="10px" 
    android:layout_height="wrap_content" 
    android:text="I am textview 2"
    />
    
</LinearLayout>
 

 

 

怎麼樣,現在清楚了吧? 至於weight,大家可以下去調試,下節課我將講解。

 

我上傳的附件是橫向和縱向相結合的佈局,可以看看。

 

搞定,打完收工!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章