框架布局(FrameLayout)是簡單的Android界面布局,它在屏幕上開辟出了一塊區(qū)域,在這塊區(qū)域中可以添加多個子控件,但是所有的子控件都被對齊到屏幕的左上角?蚣懿季值拇笮∮勺涌丶谐叽绱蟮哪莻子控件來決定。如果子控件一樣大,同一時刻只能看到上面的子控件。
FrameLayout 繼承自ViewGroup,除了繼承自父類的屬性和方法,F(xiàn)rameLayout 類中包含了自己特有的屬性和方法,如表1-1所示。
表1-2 FrameLayout常用屬性及對應(yīng)方法
屬性名稱 |
對應(yīng)方法 |
描述 |
android:foreground |
setForeground(Drawable) |
設(shè)置繪制在所有子控件之上的內(nèi)容 |
android:foregroundGravity |
setForegroundGravity(int) |
設(shè)置繪制在所有子控件之上內(nèi)容的gravity |
提示:在FrameLayout 中,子控件是通過棧來繪制的,所以后添加的子控件會被繪制在上層。
以下用一個FrameLayout的例子來加深對FrameLayout的理解。
(1)在Eclipse 中新建一個項(xiàng)目FrameLayout。打開其res/values 目錄下的strings.xml,在其中輸入如代碼清單1所示代碼。在該段代碼中聲明了應(yīng)用程序總會用到的字符串資源。
代碼清單1 strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">FrameExample</string>
<string name="big">大的</string>
<string name="middle">中的</string>
<string name="small">小的</string>
</resources>
(2)在項(xiàng)目rers/values 目錄下新建一個colors.xml,在其中輸入如代碼清單2所示代碼。該段代碼聲明了應(yīng)用程序中將會用到的顏色資源。這樣將所有顏色資源統(tǒng)一管理有助于提高程序的可讀性及可維護(hù)性。
代碼清單2 colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
<color name="green">#00FF00</color>
<color name="blue">#0000FF</color>
<color name="white">#FFFFFF</color>
</resources>
(3)打開項(xiàng)目res/layout 目錄下的main.xml 文件,將其中已有的代碼替換為如代碼清單3所示代碼。
代碼清單3 main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/FrameLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="@string/big"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="60px"
android:textColor="@color/green"
> <!-- 聲明一個TextView 控件 -->
</TextView>
<TextView
android:text="@string/middle"
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="@color/red"
> <!-- 聲明一個TextView 控件 -->
</TextView>
<TextView
android:text="@string/small"
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px"
android:textColor="@color/blue"
> <!-- 聲明一個TextView 控件 -->
</TextView>
</FrameLayout>
代碼第2~7行聲明了一個框架布局,并設(shè)置其在父控件中的顯示方式及自身的背景顏色;代碼第8~16行聲明了一個TextView控件,該控件ID為TextView01,第13 行定義了其顯示內(nèi)容的字號為60px,第14 行定義了所顯示內(nèi)容的字體顏色為綠色;代碼第17~25 行聲明了一個TextView 控件,該控件ID為TextView02,第22行定義了其顯示內(nèi)容的字號為40px,第23 行定義了所顯示內(nèi)容的字體顏色為紅色;代碼第26~34行聲明了一個TextView控件,該控件id為TextView03,第22行定義了其顯示內(nèi)容的字號為20px,第23 行定義了所顯示內(nèi)容的字體顏色為藍(lán)色。
運(yùn)行程序,在圖-1所示的運(yùn)行效果圖中可以看到,程序運(yùn)行時所有的子控件都自動地對齊到容器的左上角,由于子控件的TextView 是按照字號從大到小排列的,所以字號小的在上層。

圖-1 框架布局運(yùn)行效果圖