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鍵相同。