- 前言
- 在之前做的一个小项目中,因为对fragment的生命周期不是很熟悉,在注册和注销广播处出现了bug。
先了解下fragment app和 support v4包的区别
1.最低支持版本不同
android.app.Fragment 兼容的最低版本是 android:minSdkVersion="11" 即3.0版
android.support.v4.app.Fragment 兼容的最低版本是android:minSdkVersion="4" 即1.6版
2.需要导jar包
fragment android.support.v4.app.Fragment 需要引入包android-support-v4.jar
3.在Activity中取的方法不同
android.app.Fragment (ListFragment)getFragmentManager().findFragmentById(R.id.userList) 获得 ,继承Activity
android.support.v4.app.Fragment
(ListFragment)getSupportFragmentManager().findFragmentById(R.id.userList) 获得 ,需要继承android.support.v4.app.FragmentActivity
**下面是一个简单的布局让我们去了解下fragment的生命周期吧
<LinearLayout
android:id="@+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下一个页面"/>
<Button
android:id="@+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第一个fragment"/>
<Button
android:id="@+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第二个fragment"/>
</LinearLayout>
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/list_item"
android:layout_centerHorizontal="true"
></FrameLayout>
</RelativeLayout>
、、、
我们就以第一个fragment的生命周期为例,并且是默认加载的一个。
1. 当程序启动时即在MainActivity,在logcat可以看到:
Paste_Image.png2. 当切换到第二个fragment时, logcat无输出。
当点击跳转到下一个页面(SecondActivity)的时候,在logcat可以看到:
Paste_Image.png3. 当点击返回或者退回键的时候, 在logcat可以看到:
Paste_Image.png4.当按Home键的时候, 在logcat可以看到:
Paste_Image.png5.当我退出程序时,在logcat可以看到:
Paste_Image.png相信大家对fragment的生命周期也有一定的了解了吧。