1.FrameLayout類簡介
FrameLayout幀布局在屏幕上開辟出了一塊區域,在這塊區域中可以添加多個子控件,但是所有的子控件都被對齊到屏幕的左上角。幀布局的大小由子控件中尺寸最大的那個子控件來決定。如果子控件一樣大,同一時刻只能看到最上面的子控件。
FrameLayout繼承自ViewGroup,除了繼承自父類的屬性和方法,FrameLayout類中包含了自己特有的屬性和方法,如下表所示。
屬性名稱 | 對應方法 | 描述 |
android:foreground | setForeground(Drawable) | 設置繪制在所有子控件之上的內容 |
android:foregroundGravity | setForegroundGravity(int) | 設置繪制在所有子控件之上內容的gravity屬性 |
在FreamLayout中,子控件是通過棧來繪制的,所以后添加的子控件會被控制在上層。
2.幀布局案例
本節將通過一個案例對幀布局的用法進行說明,開發步驟如下。
1)新建一個項目Android_Sample_3_4。
2)打開其res/values目錄下的strings.xml,在其中輸入如下代碼。
1: <?xml version="1.0" encoding="utf-8"?>2: <resources>3: <string name="app_name">FrameExample</string>4: <string name="big">大的</string>5: <string name="middle">中的</string>6: <string name="small">小的</string>7: </resources>
3)在項目res/values目錄下新建一個colors.xml,在其中輸入如下代碼。
1: <?xml version="1.0" encoding="UTF-8"?>2: <resources>3: <color name="red">#FF0000</color>4: <color name="green">#00FF00</color>5: <color name="blue">#0000FF</color>6: <color name="white">#FFFFFF</color>7: </resources>
4)打開項目res/layout目錄下的main.xml文件,將其中已有的代碼替換為如下代碼。
1: <?xml version="1.0" encoding="utf-8"?>2: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"3: android:id="@+id/FrameLayout01"4: android:layout_width="fill_parent"5: android:layout_height="fill_parent"6: android:background="@color/white" >7:8: <TextView9: android:id="@+id/TextView01"10: android:layout_width="wrap_content"11: android:layout_height="wrap_content"12: android:text="@string/big"13: android:textColor="@color/green"14: android:textSize="60dp" >15: </TextView>16:17: <TextView18: android:id="@+id/TextView02"19: android:layout_width="wrap_content"20: android:layout_height="wrap_content"21: android:text="@string/middle"22: android:textColor="@color/red"23: android:textSize="40dp" >24: </TextView>25:26: <TextView27: android:id="@+id/TextView03"28: android:layout_width="wrap_content"29: android:layout_height="wrap_content"30: android:text="@string/small"31: android:textColor="@color/blue"32: android:textSize="20dp" >33: </TextView>34:35: </FrameLayout>
第2~6行聲明了一個幀布局,並設置其在父控件中的顯示方式及自身的背景顏色。
第8~15行聲明了一個TextView控件,該控件id為TextView01,第14行定義了其顯示內容的字號為60dp,第13行定義了所顯示內容的字體顏色為綠色。
第17~24行聲明了一個TextView控件,該控件id為TextView02,第23行定義了其顯示內容的字號為40dp,第22行定義了所顯示內容的字體顏色為紅色。
第26~33行聲明了一個TextView控件,該控件id為TextView03,第32行定義了其顯示內容的字號為20dp,第31行定義了所顯示內容的字體顏色為藍色。
5)進行Activity部分的開發。打開程序的Activity文件 Android_Sample_3_4Activity.java ,在其中輸入如下代碼。默認情況不需要做修改。
1: package wyf.jc;
2:3: import android.app.Activity;
4: import android.os.Bundle;
5:6: public class Android_Sample_3_4Activity extends Activity {7: @Override8: public void onCreate(Bundle savedInstanceState) {9: super.onCreate(savedInstanceState);
10: setContentView(R.layout.main);11: }12: }
完成了上述步驟的開發后,運行Android_Sample_3_4,其效果如下圖所示。
在圖中可以看到,程序運行時所有的子控件都自動地對齊到容器的左上角,由於子控件的TextView是按照字號從大到小排列的,所以字號小的在最上層。
作者:銀月蓮
出處:http://www.cnblogs.com/moonsilvering
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,包括文章,代碼,圖片等本站內所有資源,否則保留追究法律責任的權利。