學習安卓開發[2] - 在Activity中託管Fragment

在上一篇學習安卓開發[1]-程序結構、Activity生命週期及頁面通訊中,學習了Activity的一些基礎應用,基於這些知識,能夠構建一些簡單的APP了,但這還遠遠不夠,本節會學習如何使用Activity託管Fragment的方式來進行開發java

[TOC]android

爲何須要Fragment

單純使用Activity的侷限

爲何須要Fragment呢,這要從Activity的侷限提及。在前面使用Activity的過程當中已經發現,Activity很容易被銷燬重建,甚至是在設備旋轉的時候也會被銷燬,爲了返回以前的狀態須要保存各類界面相關的信息。 再來假設一種比較常見的場景,一個列表界面+明細界面構成的應用,若是用兩個Activity來實現也能夠,但若是用戶在平板設備上運行應用,則最好能同時顯示列表和明細記錄,相似網易雲、QQ那樣在屏幕左側約1/3的區域顯示列表,右側剩餘的區域展現詳細信息,這是使用兩個Activity沒法知足的;另外,查看可否在用戶想查看下一條明細時沒必要回退、再點擊進入明細界面,而是採用在屏幕橫向滑動切換到下一條這樣的快捷手勢呢,這也是兩個Activity沒法知足的。ide

Fragment介紹

接下來該是Fragment隆重登場的時候了,能夠說Fragment就是爲了應對UI的靈活需求而生的,Fragment是在API 11中開始引入的,當時Google發佈了第一臺平板設備。 那麼什麼是Fragment呢,Fragment是一種控制器對象,能夠在Activity的託管下進行用戶界面的管理,受其管理的界面能夠是整個屏幕區域,也能夠是一小部分,Fragment(碎片)就是這個意思。 要讓Activity可以託管Fragment,則須要activity視圖預留fragment插入其中的位置。一個activity視圖中能夠插入過個fragment視圖。Fragment自己沒有在屏幕上顯示視圖的能力,因此它必須放置在Activity的視圖層級中。學習

如何使用Fragment

代碼實現
容器視圖和Activity

在文件activity_fragment.xml中定義容器視圖:操作系統

<FrameLayout android:id="@+id/fragment_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

在Activity中定義了一個用於放置Fragment的FrameLayout,這個容器視圖能夠託管任意的Fragment。 對應Activity的代碼在CrimeActivity.java爲:code

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_fragment);

	FragmentManager fm = getSupportFragmentManager();
	Fragment fragment = fm.findFragmentById(R.id.fragment_container);
	if (fragment == null) {
		fragment = new CrimeFragment();
		fm.beginTransaction()
				.add(R.id.fragment_container, fragment)
				.commit();
	}
}
FragmentManager

這段代碼的做用是:在資源ID爲R.id.fragment_container的FrameLayout容器中,找到fragment,而後判斷獲取的fragment是否爲空,若是爲空則建立新的名爲CrimeFragment的Fragment實例,將其添加到FragmentManager所維護的隊列中,並在容器R.id.fragment_container中顯示。 除了這種用代碼將fragment交給Activity託管的方式,還能夠在xml中直接將fragment簽入activity,但爲了可以動態地更換fragment,惟一能採用的即是前面採用的代碼的方式。 在設備旋轉或回收內存時,Android系統會銷燬Activity,但FragmentManager會將fragment隊列保存下來。Activity被重建時,新的FragmentManager會首先獲取保存的隊列(這就是使用了Fragment後,不會有像以前那樣旋轉就會設備致使狀態丟失的現象的緣由)。因此代碼裏會先判斷fragment是否爲null,只有爲null的時候纔會從新向隊列中添加fragment。xml

Fragment的生命週期

Fragment的生命週期以下圖所示: 可見Fragment的生命週期與Activity的生命週期很是相似,實際上Fragment的許多方法對應着activity的生命週期方法。 Fragment的onCreate方法:對象

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
}

Activity的onCreate方法:blog

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
}

二者的區別在於Fragment.OnCreate()是公共方法,而Activity.OnCreate()是受保護方法,Activity的生命週期方法由操做系統調用,而Fragment的生命週期方法則是由託管它的Activity調用的。生命週期

相關文章
相關標籤/搜索