Fragment 11個生命周期:
1.onAttach(Activity) 連接宿主Activity
2.onCreate(Bundle) 創(chuàng)建Fragment
3.onCreateView(LayoutInflater, ViewGroup, Bundle)創(chuàng)建Fragment視圖
4.onActivityCreated(Bundle) 當(dāng)宿主Activity的onCreate()執(zhí)行完之后調(diào)用
5.onStart()
6.onResume()
7.onPause()
8.onStop()
9.onDestroyView() 銷毀Fragment視圖,與onCreateView對應(yīng)
10.onDestroy() 銷毀Fragment,與onCreate對應(yīng)
11.onDetach() 與宿主Activity斷開連接,與onAttach對應(yīng)
Fragment生命周期的流程
1、當(dāng)Activity創(chuàng)建時,調(diào)用Fragment的onAttach->onCreate->onCreateView->onActivityCreated
2、當(dāng)Activity啟動時,調(diào)用Fragment的onStart
3?當(dāng)Activity獲取焦點時,調(diào)用Fragment的onResume
4?當(dāng)跳轉(zhuǎn)到另一個Activity時,調(diào)用Fragment的onPause-->onStop
5?當(dāng)返回Activity時,調(diào)用Fragment的onStart->onResume
6?銷毀Activity時,調(diào)用Fragment的onDestroyView->onDestory->onDetach
Fragment簡單使用
Fragment :在Activity中使用的碎片,有自己的布局、生命周期和輸入事件
使用Fragment步驟:
1、創(chuàng)建類,并繼承Fragment
2、重寫Fragment的onCreateView()生命周期方法,并返回一個View
Fragment使用方式:
靜態(tài)加載:
在布局文件中使用
動態(tài)加載:
? ??????使用FragmentManager:
? ??????????????????????作用:管理多個Frament之間的交互和傳值的
? ??????????????????????android 3.0以前版本:當(dāng)前Activity需要繼承FragmentActivity并引入v4包
? ??????????????????????Activity.getFragmentManager() 3.0以后
? ??????????????????????FragmentActivity.getSupportFragmentManager() 3.0以前,引用v4包
? ??????????????????????FragmentTransaction beginTransaction() 獲取Fragment事務(wù)處理對象
????????使用FragmentTransaction:
? ??????????????????????作用:Fragment的處理事處類,可以在指定的ViewGroup上增加、更新、刪除Fragment
? ??????????????????????add(int containerViewId, Fragment fragment) 將Fragment對象增加到指定的控件上
? ??????????????????????replace(int containerViewId, Fragment fragment, String tag) 替換指定控件上的Fragment
? ??????????????????????commit() 提交本次事務(wù)處理
Fragment傳值:
????????????????Bundle方式:
????????????????????????????????通過Fragment.setArguments(Bundle)傳值,這種方式只適用還沒有顯示的Fragment
? ??????????????????????????????在Fragment中,通過Fragment.getArguments()獲取Bundle
? ??????????????接口回調(diào)方式:
? ??????????????????????????????Fragment向宿主Activity回傳數(shù)據(jù):
? ??????????????????????????????????????????????1、在Fragment中創(chuàng)建公共接口,定義一個方法形式參數(shù)為Bundle
? ??????????????????????????????????????????????2、聲明私有的接口變量
? ??????????????????????????????????????????????3、在onAttach方法中完成接口變量的實例化
? ??????????????????????????????????????????????4、宿主Activity實現(xiàn)Fragment中的接口,并實現(xiàn)回傳方法
Fragment與回退棧:
? ??????????作用:因在同一ViewGroup中顯示多個Fragment,因此需要回退到上一次的Fragment時,需要回退棧
? ??????????FragmentTransaction.addToBackStack(String name) 將當(dāng)前的Fragment增加到回退棧中