關於框架布局是在無特別指定的情況下將所有的控件放在屏幕布局的左上角,並且其中的每一個組件都是一幀(因此也叫作幀布局),后面的組件依次疊放在前邊的控件上;FrameLayout布局中存在以下兩個常用的關於前景的屬性
android:foreground |
設置幀布局容器的前景圖像 |
android:foregroundGravity |
設置前景圖像顯示的位置 |
貼下以下代碼,測試幀布局的特點與前景屬性
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#efe869" android:foreground="@drawable/yueliang" android:foregroundGravity="bottom|right"> <TextView android:id="@+id/tv0" android:layout_width="300dp" android:layout_height="300dp" android:background="#adecf5"/> <TextView android:id="@+id/tv1" android:layout_width="250dp" android:layout_height="250dp" android:background="#456123"/> <TextView android:id="@+id/tv2" android:layout_width="200dp" android:layout_height="200dp" android:background="#a95656"/> <TextView android:id="@+id/tv3" android:layout_width="150dp" android:layout_height="150dp" android:background="#485a92"/> </FrameLayout>
可以觀察到布局的運行效果如圖所示:左上角四個TextView依次疊加排布。右下角是一個前景,設置前景的位置為右下。
當然啦,如果全部的組件在FrameLayout中都處於左上角,那么肯定看起來有些別扭,因此我們可以在FrameLayout布局文中內,通過指定其子控件的android:layout_gravity屬性,控制子控件在布局文件中所處的位置。
FrameLayout相對於其他的布局,主要的好處就是圖層的設計,圖層之間可以相互疊加,例如LinearLayout就只能將后邊的組件給擠出去了。當然,像之前所介紹的RelativeLayout也可以實現疊加的效果。另外就是FrameLayout比較適用於自定義View與碎片(也相當於是一個Activity)中。