原創文章,若有轉載,請註明出處:http://blog.csdn.net/yihui823/article/details/6702273android
FrameLayout是最簡單的佈局了。全部放在佈局裏的控件,都按照層次堆疊在屏幕的左上角。後加進來的控件覆蓋前面的控件。佈局
在FrameLayout佈局裏,定義任何空間的位置相關的屬性都毫無心義。控件自動的堆放在左上角,根本不聽你的控制。ui
看如下的例子:spa
<?xml version="1.0" encoding="utf-8"?>.net
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"xml
android:layout_width="fill_parent"blog
android:layout_height="fill_parent"遊戲
>ip
<TextView utf-8
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="50dip"
android:textColor="#ffffff"
android:text="第一層"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dip"
android:textColor="#ffff00"
android:text="第二層"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:textColor="#ff00ff"
android:text="第三層"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#00ffff"
android:text="第四層"/>
</FrameLayout>
效果以下圖:layoutpic001
咱們如今來嘗試改變一下他們的位置。把第一個和第二個文本框改爲:
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="50dip"
android:textColor="#ffffff"
android:text="第一層"/>
<TextView
android:id="@+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dip"
android:textColor="#ffff00"
android:layout_toRightOf="@id/tv1"
android:text="第二層"/>
也就是說,讓第二個文本框放在第一個文本框的右邊。咱們來看看效果。看到了沒?仍是同樣的不變吧。
咱們來嘗試下android:gravity屬性。把第三個文本框改爲:
<TextView
android:id="@+id/tv3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:textColor="#ff00ff"
android:gravity="right"
android:text="第三層"/>
看看效果如何?天哪!居然沒有覆蓋,而是錯開了!!!
layoutpic002
首先呢,咱們不要大驚小怪。這個現象並不說明FrameLayout失效了。gravity屬性,是控制控件內部文本的格式的。而咱們看咱們控件的寬的屬性是什麼?是「fill_parent」,也就是說,咱們文本框的寬度就是屏幕的寬度。那麼android:gravity="right"文本靠右,而文本框自己仍是左上堆疊在一塊兒的。不信,咱們再來改改:
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dip"
android:textColor="#ff00ff"
android:gravity="right"
android:text="第三層"/>
咱們讓第三個文本框的寬度自適應,也就是保證顯示全文字便可。這個時候看一下效果呢?是否是打回原形啦?哈哈哈。
咱們再來試試」 android:layout_centerVertical」屬性。把第四個文本框改爲:
<TextView
android:id="@+id/tv4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#00ffff"
android:layout_centerVertical="true"
android:text="第四層"/>
效果如何?沒任何效果!
總結一下,通過以上的3個實驗,咱們知道FrameLayout根本沒法控制他的子控件的位置。全部的控件都是左上對其。可是控件自己是能夠控制本身內部的佈局的。因此利用透明,也是能夠完成一些簡單的功能的。例如屏幕四個角各顯示一些文字(是顯示文字,無法放置控件)。由於每一層覆蓋下一層的時候,若是用透明背景,則下一層不會被背景覆蓋。
什麼是透明背景?這個……說來話長啦。偷個懶,下次寫一下透明的處理。
是否是有人會問,這麼簡單的Layout有什麼用?我想仍是有它存在的價值的。
當你須要本身寫一個View的時候,在View裏面已經完成了你的邏輯(例如遊戲^_^),那麼這個View只須要一個容器放置,就可使用FrameLayout了。雖然用其餘的佈局也能夠,可是用最簡單的不是更省系統資源麼。