Android 布局之FrameLayout
1 FrameLayout簡介
對於FrameLayout,官方介紹是:
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.
即,設計FrameLayout是為了顯示單一項widget。通常,不建議使用FrameLayout顯示多項內容;因為它們的布局很難調節。不用layout_gravity屬性的話,多項內容會重疊;使用layout_gravity的話,能設置不同的位置。layout_gravity可以使用如下取值:
top
將對象放在其容器的頂部,不改變其大小.
bottom
將對象放在其容器的底部,不改變其大小.
left
將對象放在其容器的左側,不改變其大小.
right
將對象放在其容器的右側,不改變其大小.
center_vertical
將對象縱向居中,不改變其大小.
垂直對齊方式:垂直方向上居中對齊。
fill_vertical
必要的時候增加對象的縱向大小,以完全充滿其容器.
垂直方向填充
center_horizontal
將對象橫向居中,不改變其大小.
水平對齊方式:水平方向上居中對齊
fill_horizontal
必要的時候增加對象的橫向大小,以完全充滿其容器.
水平方向填充
center
將對象橫縱居中,不改變其大小.
fill
必要的時候增加對象的橫縱向大小,以完全充滿其容器.
clip_vertical
附加選項,用於按照容器的邊來剪切對象的頂部和/或底部的內容. 剪切基於其縱向對齊設置:頂部對齊時,剪切底部;底部對齊時剪切頂部;除此之外剪切頂部和底部.
垂直方向裁剪
clip_horizontal
附加選項,用於按照容器的邊來剪切對象的左側和/或右側的內容. 剪切基於其橫向對齊設置:左側對齊時,剪切右側;右側對齊時剪切左側;除此之外剪切左側和右側.
水平方向裁剪
注意: 區分“android:gravity”和“android:layout_gravity”。
android:gravity :是對控件本身來說的,是用來設置“控件自身的內容”應該顯示在“控件自身體積”的什么位置,默認值是左側。
android:layout_gravity:是相對於控件的父元素來說的,設置該控件在它的父元素的什么位置。
2 FrameLayout示例
創建一個activity,包含2組FrameLayout:1組設置android:layout_gravity屬性,另1組不設置android:layout_gravity屬性。
layout文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- 示例1 FrameLayout內容重疊 --> <TextView android:text="示例1, FrameLayout內容重疊" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <FrameLayout android:layout_width="300dp" android:layout_height="80dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是TextView,內容比較長" android:background="#ff0000"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ffff00" android:text="我是按鈕"/> </FrameLayout> <!-- 示例2 FrameLayout使用layout_gravity屬性 --> <TextView android:text="示例2, 設置layout_gravity" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <FrameLayout android:layout_width="300dp" android:layout_height="120dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="文本居左" android:background="#ff0000" android:gravity="center" android:layout_gravity="left" android:layout_margin="10dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="文本居中" android:background="#ffff00" android:gravity="center" android:layout_gravity="center"/> </FrameLayout> </LinearLayout>
點擊下載:源代碼
運行效果:如圖