Like activities, fragments has their own life cycle. Understanding the lifecycle of fragments allows you to save instances of them when they are destroyed so that they can revert to their previous state when they are created again. The following example tests the different states of the fragments.
1. Create a fragment subclass: Fragment1.java.
public class Fragment1 extends Fragment {@Override public View oncreateview (Layoutinflater inflater, VIEWGR
OUP container, Bundle savedinstancestate) {log.d ("Fragment 1", "Oncreateview"); ---Inflate the layout for this fragment---return inflater.inflate (R.LAYOUT.FRAGMENT1, cont
Ainer, false);
@Override public void Onattach (activity activity) {Super.onattach);
LOG.D ("Fragment 1", "Onattach"); @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstanc
Estate);
LOG.D ("Fragment 1", "onCreate"); @Override public void onactivitycreated (Bundle savedinstancestate) {SUPER.ONACTIVITYCR
Eated (savedinstancestate);
LOG.D ("Fragment 1", "onactivitycreated"); } @Override public void OnStarT () {super.onstart ();
LOG.D ("Fragment 1", "OnStart");
@Override public void Onresume () {super.onresume ();
LOG.D ("Fragment 1", "Onresume");
@Override public void OnPause () {super.onpause ();
LOG.D ("Fragment 1", "OnPause");
@Override public void OnStop () {super.onstop ();
LOG.D ("Fragment 1", "onStop");
@Override public void Ondestroyview () {Super.ondestroyview ();
LOG.D ("Fragment 1", "Ondestroyview");
@Override public void OnDestroy () {Super.ondestroy ();
LOG.D ("Fragment 1", "OnDestroy");
@Override public void Ondetach () {Super.ondetach ();
LOG.D ("Fragment 1", "Ondetach"); }
}
2. Press CTRL+F11 to convert the simulator to "Horizontal screen mode".
3. Press F11 to Debug.
4. When the application is loaded, the Logcat window has the following display.
03-27 12:23:32.255:d/fragment 1 (704): Onattach
03-27 12:23:32.255:d/fragment 1 (704): OnCreate
03-27 12:23:32.255:d/fragment 1 (704): Oncreateview
03-27 12:23:32.274:d/fragment 1 (704): onactivitycreated
03-27 12:23:32.274:d/fragment 1 (704): OnStart
03-27 12:23:32.286:d/fragment 1 (704): Onresume
5. Press the Home key, the Logcat window has the following display.
03-27 12:25:23.174:d/fragment 1 (704): OnPause
03-27 12:25:25.174:d/fragment 1 (704): OnStop
6. Press home key not to put, re-enter the application, the Logcat window has the following display.
03-27 12:26:21.505:d/fragment 1 (704): OnStart
03-27 12:26:21.505:d/fragment 1 (704): Onresume
7. Press the return key, the Logcat window has the following display.
03-27 12:27:54.384:d/fragment 1 (704): OnPause
03-27 12:27:55.324:d/fragment 1 (704): OnStop
03-27 12:27:55.324 : D/fragment 1 (704): Ondestroyview
03-27 12:27:55.324:d/fragment 1 (704): OnDestroy 03-27 12:27:55.324:d/
Fragment 1 (704): Ondetach