Slide show

Total Pageviews

Powered by Blogger.

Translate

Search This Blog

Pages

Differences between Activity lifecycle and Fragment lifecyle in Android

Fragment is a part of an activity, which contributes its own UI to that activity. Fragment can be thought like a sub activity. Fragments are used to efficiently use the space in wider screen devices.
An activity may contain 0 or multiple number of fragments based on the screen size. A fragment can be reused in multiple activities, so it acts like a reusable component in activities.
A fragment can't exist independently. It should be always part of an activity. Where as activity can exist with out any fragment in it.
A fragment lifecycle is more complex than the activity lifecycle because it has more states. Lifecycle states are shown below:
enter image description here
onInflate
At very beginning of the fragment life the method onInflate is called. In this method we can save some configuration parameter and some attributes define in the XML layout file.
onAttach
After this step onAttach is called. This method is called as soon as the fragment is “attached” to the “father” activity and we can this method to store the reference about the activity.
onCreate
It is one of the most important step, our fragment is in the creation process. This method can be used to start some thread to retrieve data information, maybe from a remote server. The onCreateView is the method called when the fragment has to create its view hierarchy.During this method we will inflate our layout inside the fragment.
During this phase we can’t be sure that our activity is still created so we can’t count on it for some operation. We get notified when the “father” activity is created and ready in the onActivityCreated.
From now on, our activity is active and created and we can use it when we need.
onStart
The next step is onStart method. Here we do the common things as in the activity onStart, during this phase our fragment is visible but it isn’t still interacting with the user.
onResume
When the fragment is ready to interact with user onResume is called.
Then it can happen that the activity is paused and so the activity’s onPause is called. Well onPausefragment method is called too.
After it, it can happen that the OS decides to destroy our fragment view and so onDestroyView is called. After it, if the system decides to dismiss our fragment it calls onDestroy method.
Here we should release all the connection active and so on because our fragment is close to die. Even if it is during the destroy phase it is still attached to the father activity. The last step is detach the fragment from the activity and it happens when onDetach is called.
I hope you can understand from this.
Thanks.

No comments:

vehicles

business

health