Fragment與Activity簡單使用,包括二者之間的關聯與生命週期

一、概論

隨着Android系統的多樣化,不僅僅在手機上,在平板、電視等設備上應用的也越來越多,這樣就會有一個需要適應不同屏幕的問題。在Android3.0之後,谷歌推出了Fragment,Fragment在Android中被稱爲碎片。
我們可以把Fragment看作是Activity的一個界面或者組成部分,而且Fragment具有與Activity很相似的生命週期,我們可以在Activity中動態的添加或者移除某個Fragment。

二、生命週期

(一)Fragment的生命週期

谷歌技術文檔上Fragment的生命週期截圖爲:



爲了更直觀的看到Fragment切換時候的生命週期,我們在每個生命週期方法中打印一句Log日誌,更直觀的看到Fragment在創建、隱藏、顯示、銷燬時候的生命週期。

1.第一次打開應用:



2.按home鍵隱藏應用:


3.從後臺切換回來時:


4.退出應用時:



(二)Fragment的生命週期與Activity之間的關係

我們會發現跟Activity對比,Fragment會多幾個生命週期,等下會介紹這你個不同生命週期方法的作用,先來看一張谷歌技術文檔上Fragment與Activity生命週期之間的關係圖:



onCreate( )、onStart( )、 onStop( )等生命週期方法是跟Activity的生命週期一一對應的,這裏不做詳細介紹,最主要的就是跟Activity不一樣的生命週期。

(1)onAttach( ):當Fragment與Activity綁定、關聯的時候調用;
(2)onCreateView( ):創建該Fragment對應的視圖,並把視圖返回給調用者,與onCreate( )的區別是你可以在onCreate( )中初始化與View無關的東西;
(3)onActivityCreated( )在Activity完成其onCreate()方法後調用;
(4)onDestroyView( ):當Fragment銷燬視圖的時候調用;
(5)onDetach( ):Fragment與Activity脫離關係的時候調用;

三、Fragment與Activity的關聯

如圖:我們要實現這種效果,上面的標題與下面的內容區域,我們分別用兩個Fragment來顯示。



Fragment與Activity關聯主要有兩種方式,一種是通過在Activity的佈局文件中寫入fragment控件,使用name屬性指定一個Fragment;另一種是在java代碼中動態的添加與刪除Fragment。

(一)在Activity佈局中關聯Fragment

這種關聯方式比較簡單,只需要在Activity的佈局文件中關聯上需要顯示的fragment控件,就是把Fragment當成普通的View一樣聲明在Activity的佈局文件中,而Activity的java代碼只需要加載自己的這個佈局即可,優點是比較快捷,可以提高複用性與維護性,缺點是移除與替換比較麻煩,xml佈局文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <fragment
        android:id="@+id/fragmentone"
        android:name="com.example.fragmentdemo.FragmentOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <fragment
        android:id="@+id/fragmenttwo"
        android:name="com.example.fragmentdemo.FragmentTwo"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

FragmentOne跟FragmentTwo的佈局這裏就不貼出來了,就是兩個簡單的TextView而已。

(二)實用java代碼關聯Fragment

實用java代碼可以動態的添加、刪除與替換Fragment,實用性更廣一些。
首先我們在Activity的佈局文件中添加兩個FrameLayout控件,用來存放要顯示的Fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <FrameLayout
        android:id="@+id/framelayoutone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </FrameLayout>
    <FrameLayout
        android:id="@+id/framelayouttwo"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>
</LinearLayout>
對應Activity中的java代碼爲:
package com.example.fragmentdemo;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Window;
import android.widget.FrameLayout;

public class MainActivity extends Activity {
	
	private FragmentOne fragmentOne;
	private FragmentTwo fragmentTwo;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.activity_main);
		
		// 初始化要顯示的兩個Fragment
		fragmentOne = new FragmentOne();
		fragmentTwo = new FragmentTwo();
		
		// 得到Fragment的管理者FragmentManager
		FragmentManager fm = getFragmentManager();
		
		// 開啓一個事務
		FragmentTransaction ft = fm.beginTransaction();
		
		/**
		 * 在FrameLayout中加載我們要顯示的Fragment,這裏我們使用了replace方法,下面我會介紹它與add的區別
		 * 參數:
		 * containerViewId:需要存放到哪個控件中;
		 * fragment:需要顯示的Fragment;
		 * tag:給Fragment定義一個標籤,方便我們取出使用等。
		 */
		ft.replace(R.id.framelayoutone, fragmentOne, "ONE");
		ft.replace(R.id.framelayouttwo, fragmentTwo, "TWO");
		
		// 最後,千萬不要忘記了使用commit提交,這點有點類似數據庫中的事務的使用
		ft.commit();	
	}
}

其中的佈局,Fragment我們都可以進行替換,所以就達到了動態創建Fragment的目的。
事務中其他的方法還有:
ft.add( ):添加一個Fragment到Activity中;
ft.remove( ):把Fragment從Activity中移除;
ft.hide( ):隱藏當前的Fragment,不會銷燬它;
ft.show( ):顯示隱藏的Fragment;
上面我們爲什麼要使用ft.replace( )呢?因爲ft.replace( )是ft.remove( )與ft.add( )的合體,相當於先移除Fragment後,再添加一個Fragment。

Fragment與Activity的簡單關聯就先介紹到這裏了,他們之間的交互與通信以後再向大家介紹,最後,附上本文的Demo:
http://download.csdn.net/detail/xiaoli100861/9220813



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章