When is onAttach called during the Fragment LifeCycle?
In activity the first method is onCreate.
onCreate of activity add the fragment and in this moment onAttach is called. like in the picture
Ref: https://github.com/xxv/android-lifecycle
Why is onAttach called before onCreate?
TL;DR:
In order to not break the design consistency amongst different UI components in android,the onCreate()
method will have similar functionality across all of them.
When linking Containers to Contents like Window to Activity and Activity to Fragment a preliminary check needs to be done to determine the state of container.
And that explains the use and position of onAttach()
in the fragment lifecycle.
Too short;Need longer:
The answer is in the archetype code itself,
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
Another example would be in Jake Wharton's ActionBarSherlock library.
Why would you want to use a method like onCreate()
which is has the same purpose in an activity ,service.
The onCreate()
is meant to handle issues with respect to that particular context creation.It does not make sense if onCreate()
is used to check the state of its container.
The second reason that I can come determine is that a fragment is designed to be activity independent.The onAttach()
provides an interface to determine the state/type/(other detail that matters to the fragment) of the containing activity with reference to the fragment before you initialize a fragment.
EDIT:
An activity exists independently and therefore has a self sustaining lifecycle.
for a fragment :
The independent lifecycle components(same as any other components):
- onCreate()
- onStart()
- onResume()
- onPause()
- onStop()
- onDestroy()
The interaction based components:
- onAttach()
- onCreateView()
- onActivityCreated()
- onDestroyView()
- onDetach()
from the documentation:
The flow of a fragment's lifecycle, as it is affected by its host
activity, (...) each successive state of the activity determines which
callback methods a fragment may receive. For example, when the
activity has received its onCreate() callback, a fragment in the
activity receives no more than the onActivityCreated() callback.Once the activity reaches the resumed state, you can freely add and
remove fragments to the activity. Thus, only while the activity is in
the resumed state can the lifecycle of a fragment change
independently.However, when the activity leaves the resumed state, the fragment
again is pushed through its lifecycle by the activity.
answering another question which came up in the comments:
Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
The design philosophy states that a Fragment is designed for reuse. A fragment (by design) could(and should) be used across multiple activities.
The onCreate
by definition is responsible to create a fragment.
Consider the case of orientation,your fragment could be:
- using different layouts in different orientations.
- applicable only in portrait orientation and not landscape
- To be used only on tables and mobile phones.
All these situations would require a check before the fragment is initialized from the android perspective(onCreate()
) and the view inflated(onCreateView()
).
Also consider the situation of a headless fragment.The onAttach()
provides you the interface required for preliminary checks.
Can a fragment's onAttach be called before the Activity's onCreate has finished?
Yes. See the documentation at https://developer.android.com/reference/android/app/Fragment.html#onCreate(android.os.Bundle). Fragment.onAttach happens before Fragment.onCreate and if the documentation for onCreate says that the activity can still be in the process of being created during this lifecycle method, then that means that it definitely can be under construction in onAttach, which happens before onCreate.
As to your specific scenario, if that is your entire onCreate of the activity, then those fragments are not hooked into the application at all; they have not been added via the fragment manager. They are only instantiated and cannot have Android lifecycle calls yet. I assume that there is something more complex going on and that fragments are being re-added after a configuration change or something when you get the crash.
Understanding Fragment's lifeCycle methods calls during fragment transaction
Does this mean that no method of current fragment is called when new fragment is added in same activity?
Correct, your first fragment A will only be affected if it's removed or replaced (case 2).
Simply adding another fragment will just display fragment B over fragment A and no life cycle callbacks should be called.
What i expected was?
onStart method of Fragment A is called since Fragment A is visible now
Again, since fragment B was added on top of A, fragment A is not affected by the removal of B.
onDestroy and onDetach method of Fragment A is NOT called.Why its not called?Bcoz as per documentation method replace removes any fragments that are already in the container and add your new one to the same container
Unlike a simple replace, when you add your replace transaction to the backstack you're actually keeping the first fragment attached to it's activity, only its view is destroyed.
Once you pop the backstack fragment B is removed and fragment A will just recreate its view - starting from onCreateView().
Related Topics
Failed to Resolve: Com.Google.Firebase:Firebase-Core:16.0.1
Preemptive Basic Auth with Httpurlconnection
Import Google Play Services Library in Android Studio
Duplicated Entries in Listview
Universal Way to Write to External Sd Card on Android
How to Remove All Callbacks from a Handler
Hosting an Executable Within Android Application
How to Download Older Google Play Services
Full Screen Videoview Without Stretching the Video
How to Select and Crop an Image in Android
Android Archive Library (Aar) VS Standard Jar
Android - Prevent White Screen at Startup
Flutter Apps Are Too Big in Size
Resize Image to Full Width and Fixed Height with Picasso
Using Custom Font in Android Textview Using Xml
What Optimizations How to Expect from Dalvik and the Android Toolchain
Convert Object to JSON in Android
Android: Textview Automatically Truncate and Replace Last 3 Char of String