Fragment的生命周期,以及用法

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增加到回退棧中

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容