Fragment的兩種添加方式下的生命周期

Fragment的添加到activity中有兩種方式,這兩種方式添加的fragment的生命周期有一點(diǎn)的區(qū)別。

1.靜態(tài)添加Fragment,將fragment直接放在activity的布局xml中。

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:baselineAligned="false" >  
  
    <fragment  
        android:id="@+id/fragment1"  
        android:name="com.harvic.com.harvicblog2.Fragment1"  
        android:layout_width="0dip"  
        android:layout_height="match_parent"  
        android:layout_weight="1" />  
  
    <fragment  
        android:id="@+id/fragment2"  
        android:name="com.harvic.com.harvicblog2.Fragment2"  
        android:layout_width="0dip"  
        android:layout_height="match_parent"  
        android:layout_weight="1" />  
  
</LinearLayout>  

這種情況下的fragment的生命周期為:
啟動(dòng)activity的時(shí)候,frament的生命周期

1.png

點(diǎn)擊home鍵,回到桌面界面的frament的生命周期

2.png

重新進(jìn)入界面時(shí),frament的生命周期

3.png

點(diǎn)擊back界退出時(shí),frament的生命周期

4.png

2.動(dòng)態(tài)添加Fragment,fragment的生命周期。

動(dòng)態(tài)添加fragment的代碼如下:

      FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction =               manager.beginTransaction();
            Fragment1 fragment1 = new Fragment1();
            transaction.add(R.id.fragment_container, fragment1);
            transaction.commit();

只要當(dāng)執(zhí)行FragmentTransaction 執(zhí)行commit()后,fragment才會(huì)走下面的生命周期方法:

Image.png

點(diǎn)擊home鍵,重新進(jìn)入界面時(shí),點(diǎn)擊back界退出時(shí)這三種情況的生命周期方法和靜態(tài)添加的相同。 這里就不說(shuō)了。
FragmentTransaction 執(zhí)行remove()時(shí):fragment生命周期方法和點(diǎn)擊back鍵相同。

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

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

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