Fragment is introduced in android API Level 11, it is designed for more feasible GUI layout.If you want to design UI layout like Master-Detail Application in iOS, fragment is very suitable. We can use a list fragment on the left to display some item, when user select on item, we will show the detail information on the right fragment. Layout of Master-Detail Application is like the left part of the below image:
Fragment is also very useful for smart-phones app. When we need to change the content of the screen, we don’t need to use a new Activity
, instead we can use fragments for app screen switches, which is much more light-weight than switches between Activities.
Just like Activity, fragment also has lifecycle states, and it’s very important for you to know when the state of a fragment will be change, and will change to which state, before you use fragments. I provided a very simple project here, which contains the basic fragment usage. The screen of the simple project, and how screens switch is indicated below:
All the three screens are fragments which are in the same activity, when we press buttons on the first scree, screen will change. From the output of logcat, we can see lifecycle state change of each fragments:
- when we press
To Fragment One
, the screen will chagne fromMainMenuFragment
to ‘FragmentOne’, and the output of logcat is:
When we switch to a new fragment, the old fragment goes toonPause
, and the new fragment will be instanced, with the following lifecycle state:onAttach -> onCreate -> onCreateView -> onActivityChanged -> onStart -> onResume. - when we press back button, screen will change from ‘FragmentOne ‘ back to ‘MainMenuFragment’ again, the output of logcat is:
and the lifecycle states of ‘FragmentOne’ is: onPause -> onStop -> onDestroyView -> onDestroy -> onDetach; and onlyonCreateView
andonResume
ofMainMenuFragment
will be called.
From the operations above , we can get the below conclusion:
onAttach
method of fragment will be called only once, when the fragment is attached to activity (you can set the activity as the fragment’s custom event listener here).onCreateView
andonResume
methods will be called every time when fragments is poped from backstack (you can use onResume method, to let the activity know which fragment is the current being shown fragment).- when we pop a fragment from back stack, the
onBackStackChanged
method ofonBackStackChangedListener
will be called after the fragment’s lifecycle chagnes. - when we send the app to background,
onStop
andonPause
methods of fragments will be called, when switch app back from background,onStart
andonResume
methods will be called.
onCreateView
, onResume
,onAttach
these three methods is the main state you should consider when using fragments, for other details, you can refer to Android Fragment Document.