Reputation: 150
From what my understanding is regarding Activities and Fragments in Android, fragment is a sub-part of the activity in which it is called.
So what I want to know is that if we finish or kill the Activity in which the fragment exists, how will it effect the fragment?
Will the fragment also get destroyed?? or is it that the state of fragment is independent of the activity containing it? Please provide a proper clarification on this...
Upvotes: 0
Views: 2156
Reputation: 11
How the Activity state affects the Fragment
Because a Fragment is always hosted by an Activity, the Fragment lifecycle is directly affected by the host Activity lifecycle. For example, when the Activity is paused, so are all Fragments in it, and when the Activity is destroyed, so are all Fragments.
Each lifecycle callback for the Activity results in a similar callback for each Fragment, as shown in the following table. For example, when the Activity receives onPause(), it triggers a Fragment onPause() for each Fragment in the Activity.
Also from official guide: "For instance, for an Activity, this (DESTROYED)state is reached right before Activity's onDestroy call" link: https://developer.android.com/reference/androidx/lifecycle/Lifecycle.State#DESTROYED
Upvotes: 1
Reputation: 123
As Fragment is embedded inside an Activity, it will be killed when Activity is killed. As contents of activity are first killed, fragment will be destroyed just before activity gets destroyed.
Upvotes: 0
Reputation: 4688
From what my understanding is regarding Activities and Fragments in Android, fragment is a sub-part of the activity in which it is called.
Yes you are right, fragments are sub parts added dynamically on run time
So what I want to know is that if we finish or kill the Activity in which the fragment exists, how will it effect the fragment?
If you kill/finish an Activity fragments will also be destroyed
NOTE: Fragment lifecycle is dependent on Activity life cycle, if an Activity is dead so the fragments are.
Building fragment on an Activity is like building 2,3 or 4 story building. If base is destroyed then other stories are not supposed to be stable. Just keep this rule in mind. This will help you with understanding. And further more you can apply logging on Activity and Fragment lifecycle.
Upvotes: 4