為什么要使用碎片F(xiàn)ragment
碎片的出現(xiàn)是為了能使一套布局適應(yīng)在不同大小尺寸的Android設(shè)備上,我們可以將Fragment理解為Activity上的一個個的碎片組成部分。
Fragment擁有自己的生命周期,并且可以接收、處理用戶的事件。而且我們還可以在程序運行時動態(tài)的添加、替換和移除某個Fragment。
創(chuàng)建與使用Fragment
首先需要在一個activity中設(shè)置一個布局作為主容器

在activity中使用FragmentManager來管理fragment,在管理器中使用beginTransaction()來開啟事務(wù),通過add()來添加具體事務(wù)(添加fragment),通過commit()來提交事務(wù)。

在按鈕事件中,使用FragmentManager中的replace()方法可以在容器中替換碎片

這種情況下,我們的Fragment與Activity共用返回棧,在fragment中返回將直接退出應(yīng)用,需要使用使用fragment模擬activity的返回棧,需要用到FragmentManager的方法addToBackStack(null),這樣在被激活的另一個Fragment中按下返回將會回到上一個這個Fragement

有時我們需要使用后退按鈕來退回到上一個Fragment,可以通過FragmentManager的popBackStack()方法手動返回

Fragment的生命周期

如圖所示是Fragment的生命周期,其中有很多函數(shù),但是我們常用的有三個
onCreate()、onCreateView()、onPause()
演示如下(轉(zhuǎn)自此處):
場景演示 : 切換到該Fragment
11-29 14:26:35.095: D/AppListFragment(7649): onAttach
11-29 14:26:35.095: D/AppListFragment(7649): onCreate
11-29 14:26:35.095: D/AppListFragment(7649): onCreateView
11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated
11-29 14:26:35.120: D/AppListFragment(7649): onStart
11-29 14:26:35.120: D/AppListFragment(7649): onResume
屏幕滅掉:
11-29 14:27:35.185: D/AppListFragment(7649): onPause
11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState
11-29 14:27:35.205: D/AppListFragment(7649): onStop
屏幕解鎖
11-29 14:33:13.240: D/AppListFragment(7649): onStart
11-29 14:33:13.275: D/AppListFragment(7649): onResume
切換到其他Fragment:
11-29 14:33:33.655: D/AppListFragment(7649): onPause
11-29 14:33:33.655: D/AppListFragment(7649): onStop
11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView
切換回本身的Fragment:
11-29 14:33:55.820: D/AppListFragment(7649): onCreateView
11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated
11-29 14:33:55.825: D/AppListFragment(7649): onStart
11-29 14:33:55.825: D/AppListFragment(7649): onResume
回到桌面
11-29 14:34:26.590: D/AppListFragment(7649): onPause
11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState
11-29 14:34:26.880: D/AppListFragment(7649): onStop
回到應(yīng)用
11-29 14:36:51.940: D/AppListFragment(7649): onStart
11-29 14:36:51.940: D/AppListFragment(7649): onResume
退出應(yīng)用
11-29 14:37:03.020: D/AppListFragment(7649): onPause
11-29 14:37:03.155: D/AppListFragment(7649): onStop
11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView
11-29 14:37:03.165: D/AppListFragment(7649): onDestroy
11-29 14:37:03.165: D/AppListFragment(7649): onDetach