Android - retaining fragment? - android

Hi I have a question about retaining fragment when Activity is recreated.
I heard one way is to use setRetainFragment(true) in the onCreate method.
Question is - how is this different from keeping track of private Fragment property in Activity so that I always have the same Fragment object throughout the activity's lifetime? Thanks!

setRetainInstance(true): The Fragment's state will be retained (and not destroyed!) across configuration changes (e.g. screen rotate). The state will be
retained even if the configuration change causes the "parent" Activity to be destroyed. However, the view of the Fragment gets destroyed!
Lifecycle Calls:
onPause() -> onStop() -> onDestroyView() -> onDetach()
onAttach() -> onCreateView() -> onStart() -> onResume()
setRetainInstance(false): The Fragment's state will not be retained across configuration changes (default).
Lifecycle Calls:
onPause() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach()
onAttach() -> onCreate() -> onCreateView() -> onStart() -> onResume()
Important: setRetainInstance(true) does not work with fragments on the back stack. setRetainInstance(true) is especially useful for long running operations
inside Fragments which do not care about configuration changes.

If you mean a private property it means a property within the class so each time the activity is recreated a new instance with a new private fragment is created for Example at t=t1 the instance of Activity A is created so it contains all its private variables and in t=t2 a new instance of the Activity A is created and so when you set setRetainFragment(true)the Android framework under the hood retain your fragments without recreating them and preserves it state.
You can refer to this link for further information Understanding Fragment's setRetainInstance(boolean)

Related

What is the difference between "Don't keep activities" and a Configuration change?

I am using View Model architecture component to handle the UI states and contain Business logic. It is known it survives a configuration change, but when Don't keep activities option is turned on in Developer options, a new instance of View Model is created. The activity onDestroy is called in both the cases then what is the difference between the two?
I am maintaining a state machine in the View Model and face issue in restoring it since View Model does not survive this. I cannot use Instance state since it has complex objects.
Following logs are from a sample project I tried. This has an Activity TestActivity which contains a fragment TestFragment, and TestFragment contains two fragments TestStateAFragment and TestStateBFragment
TestActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
if(savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.container_fragment_test, TestFragment())
.commitAllowingStateLoss()
}
}
TestFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Timber.i("onViewCreated")
super.onViewCreated(view, savedInstanceState)
if(savedInstanceState == null) {
childFragmentManager.beginTransaction()
.add(R.id.container_state_a, TestStateAFragment.newInstance())
.commitAllowingStateLoss()
childFragmentManager.beginTransaction()
.add(R.id.container_state_b, TestStateBFragment.newInstance())
.commitAllowingStateLoss()
}
}
TestStateAFragment.kt
private val compositeDisposable: CompositeDisposable = CompositeDisposable()
private lateinit var viewModel : TestStateAViewModel
override fun onCreate(savedInstanceState: Bundle?) {
Timber.i("onCreate")
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this, TestStateAViewModelFactory())
.get(TestStateAViewModel::class.java)
Timber.i(viewModel.toString())
}
Screen rotation :
(TestStateAFragment.kt:101)#onPause: onPause
(TestStateBFragment.kt:66)#onPause: onPause
(TestFragment.kt:72)#onPause: onPause
(TestActivity.kt:45)#onPause: onPause
(TestStateAFragment.kt:105)#onStop: onStop
(TestStateBFragment.kt:70)#onStop: onStop
(TestFragment.kt:76)#onStop: onStop
(TestActivity.kt:50)#onStop: onStop
(TestActivity.kt:23)#onSaveInstanceState: onSaveInstanceState
(TestFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestStateAFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestActivity.kt:54)#onDestroy: onDestroy
(TestStateAFragment.kt:110)#onDestroyView: onDestroyView
(TestStateBFragment.kt:75)#onDestroyView: onDestroyView
(TestFragment.kt:81)#onDestroyView: onDestroyView
(TestStateAFragment.kt:115)#onDestroy: onDestroy
(TestStateBFragment.kt:80)#onDestroy: onDestroy
(TestFragment.kt:86)#onDestroy: onDestroy
(TestFragment.kt:17)#onAttach: onAttach
(TestFragment.kt:18)#onAttach: TestFragment{984b690 (625e084e-68d8-46d6-9527-dfe2694fa5c1) id=0x7f07004c}
(TestFragment.kt:23)#onCreate: onCreate
(TestStateAFragment.kt:30)#onAttach: onAttach
(TestStateAFragment.kt:31)#onAttach: TestStateAFragment{1ff9e9a (f73d9a4a-4fb0-4e1c-b6b0-220941525ae2) id=0x7f07004d}
(TestStateAFragment.kt:39)#onCreate: onCreate
(TestStateAFragment.kt:44)#onCreate: com.example.lifecycleviewmodel.fragment.states.a.TestStateAViewModel#afc805d
(TestStateBFragment.kt:27)#onAttach: onAttach
(TestStateBFragment.kt:28)#onAttach: TestStateBFragment{908b1a7 (a5fa2bce-9b3b-4474-ae2a-0a891f289f65) id=0x7f07004e}
(TestStateBFragment.kt:33)#onCreate: onCreate
(TestActivity.kt:34)#onStart: onStart
(TestFragment.kt:34)#onCreateView: onCreateView
(TestFragment.kt:40)#onViewCreated: onViewCreated
(TestStateAFragment.kt:67)#onCreateView: onCreateView
(TestStateAFragment.kt:73)#onViewCreated: onViewCreated
(TestStateBFragment.kt:44)#onCreateView: onCreateView
(TestStateBFragment.kt:50)#onViewCreated: onViewCreated
(TestFragment.kt:61)#onStart: onStart
(TestStateAFragment.kt:90)#onStart: onStart
(TestStateBFragment.kt:55)#onStart: onStart
(TestActivity.kt:40)#onResume: onResume
(TestFragment.kt:66)#onResume: onResume
(TestStateAFragment.kt:95)#onResume: onResume
(TestStateBFragment.kt:60)#onResume: onResume
Don't keep activities off :
(TestStateAFragment.kt:101)#onPause: onPause
(TestStateBFragment.kt:66)#onPause: onPause
(TestFragment.kt:72)#onPause: onPause
(TestActivity.kt:45)#onPause: onPause
(TestStateAFragment.kt:105)#onStop: onStop
(TestStateBFragment.kt:70)#onStop: onStop
(TestFragment.kt:76)#onStop: onStop
(TestActivity.kt:50)#onStop: onStop
(TestActivity.kt:23)#onSaveInstanceState: onSaveInstanceState
(TestFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestStateAFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestActivity.kt:30)#onRestart: onRestart
(TestActivity.kt:34)#onStart: onStart
(TestFragment.kt:61)#onStart: onStart
(TestStateAFragment.kt:90)#onStart: onStart
(TestStateBFragment.kt:55)#onStart: onStart
(TestActivity.kt:40)#onResume: onResume
(TestFragment.kt:66)#onResume: onResume
(TestStateAFragment.kt:95)#onResume: onResume
(TestStateBFragment.kt:60)#onResume: onResume
(TestStateAFragment.kt:101)#onPause: onPause
(TestStateBFragment.kt:66)#onPause: onPause
(TestFragment.kt:72)#onPause: onPause
(TestActivity.kt:45)#onPause: onPause
(TestStateAFragment.kt:105)#onStop: onStop
(TestStateBFragment.kt:70)#onStop: onStop
(TestFragment.kt:76)#onStop: onStop
(TestActivity.kt:50)#onStop: onStop
(TestActivity.kt:23)#onSaveInstanceState: onSaveInstanceState
(TestFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestStateAFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
Don't keep activities ON :
(TestStateAFragment.kt:101)#onPause: onPause
(TestStateBFragment.kt:66)#onPause: onPause
(TestFragment.kt:72)#onPause: onPause
(TestActivity.kt:45)#onPause: onPause
(TestStateAFragment.kt:105)#onStop: onStop
(TestStateBFragment.kt:70)#onStop: onStop
(TestFragment.kt:76)#onStop: onStop
(TestActivity.kt:50)#onStop: onStop
(TestActivity.kt:23)#onSaveInstanceState: onSaveInstanceState
(TestFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestStateAFragment.kt:55)#onSaveInstanceState: onSaveInstanceState
(TestActivity.kt:54)#onDestroy: onDestroy
(TestStateAFragment.kt:110)#onDestroyView: onDestroyView
(TestStateBFragment.kt:75)#onDestroyView: onDestroyView
(TestFragment.kt:81)#onDestroyView: onDestroyView
(TestStateAFragment.kt:115)#onDestroy: onDestroy
(TestStateBFragment.kt:80)#onDestroy: onDestroy
(TestFragment.kt:86)#onDestroy: onDestroy
2019-09-18 20:30:10.503 31473-31473/com.example.lifecycleviewmodel W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#d382041
(TestFragment.kt:17)#onAttach: onAttach
(TestFragment.kt:18)#onAttach: TestFragment{544b1c5 (625e084e-68d8-46d6-9527-dfe2694fa5c1) id=0x7f07004c}
(TestFragment.kt:23)#onCreate: onCreate
(TestStateAFragment.kt:30)#onAttach: onAttach
(TestStateAFragment.kt:31)#onAttach: TestStateAFragment{ea5f827 (f73d9a4a-4fb0-4e1c-b6b0-220941525ae2) id=0x7f07004d}
(TestStateAFragment.kt:39)#onCreate: onCreate
(TestStateAFragment.kt:44)#onCreate: com.example.lifecycleviewmodel.fragment.states.a.TestStateAViewModel#fa43f72
(TestStateBFragment.kt:27)#onAttach: onAttach
(TestStateBFragment.kt:28)#onAttach: TestStateBFragment{f66bb79 (a5fa2bce-9b3b-4474-ae2a-0a891f289f65) id=0x7f07004e}
(TestStateBFragment.kt:33)#onCreate: onCreate
(TestActivity.kt:34)#onStart: onStart
(TestFragment.kt:34)#onCreateView: onCreateView
(TestFragment.kt:40)#onViewCreated: onViewCreated
(TestStateAFragment.kt:67)#onCreateView: onCreateView
(TestStateAFragment.kt:73)#onViewCreated: onViewCreated
(TestStateBFragment.kt:44)#onCreateView: onCreateView
(TestStateBFragment.kt:50)#onViewCreated: onViewCreated
(TestFragment.kt:61)#onStart: onStart
(TestStateAFragment.kt:90)#onStart: onStart
(TestStateBFragment.kt:55)#onStart: onStart
(TestActivity.kt:40)#onResume: onResume
(TestFragment.kt:66)#onResume: onResume
(TestStateAFragment.kt:95)#onResume: onResume
(TestStateBFragment.kt:60)#onResume: onResume
So where do these two scenarios differ exactly and is there a way to determine which one took place?
When a configuration change occurs, the Android framework will call onRetainNonConfigurationInstance() on your Activity. You can return any object you want to. Then Android will destroy your Activity and immediate create a new instance. In onCreate() of the new instance you can call getLastNonConfigurationInstance(). If the Activity was recreated due to a configuration change, the object that you returned from onRetainNonConfigurationInstance() will be returned here. Otherwise the call returns null. In this case you can tell when your Activity was recreated due to a configuration change, and when it was (re)started for other reasons.
The developer option "Don't keep activities" is not something that you usually have to deal with, as normal users should never have it enabled. You can use it for testing purposes to ensure that your Activity properly recovers in case Android decides to kill it off.
In reality, Android usually doesn't kill off individual activities. If Android needs to recover resources from background applications it usually just kills off the entire OS process. However, I have recently seen some situations on some devices where Android does indeed kill off individual activities when an app is in the background. When the user then returns to the app, Android will recreate the Activity. In this case you will get null returned from getLastNonConfigurationInstance(), but you would get a non-null Bundle in the onCreate() call and you would also get a non-null Bundle in the onRestoreInstanceState(). So you should be able to tell the difference between:
Activity created for the first time
Activity instance created after configuration change
Activity instance recreated after Android killed it off and user returned to it
See https://developer.android.com/reference/android/app/Activity.html?hl=en#onRetainNonConfigurationInstance()
I'm not exactly sure of your requriements, but this information should help.
ViewModel survives a configuration change since FragmentActivity stores it during onRetainNonConfigurationInstance, which is called during the process of configuration change of Activity. I think when "do not keep activities" mode is turned on, or when Activity is recycled by Android system, it does not belong to the process of configuration change. So onRetainNonConfigurationInstance will NOT be called and ViewModel will not survive after Activity recreates.

Difference between creating a new fragment and getting an existing one from the manager on rotation

It seems whether I set retainInstance to true or not, when I rotate the device, I get an existing fragment. The difference is that if I set it to true, I get "test = yes!", otherwise I get "test = no!" after rotating the device after clicking the test button to change test. That is, the member variable is kept, if I retain the instance.
But as I have said, even if I do not retain it, I get an existing fragment from the manager, anyway (always get "Reusing existing" on rotation). In that case, if all member variables are lost and the views of the fragment are recreated, what are kept? What is the point of getting an existing instance of the fragment?
In the activity's onCreate,
var frag = supportFragmentManager.findFragmentById(R.id.frame)
if(frag == null)
{
frag = Fragment1.newInstance("", "");
}
else
{
Log.d("sss", "Reusing exsiting");
}
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame, frag)
transaction.commit()
In the fragment,
var test = "no!";
override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
Log.d("sss", "test = " + test);
testButton.setOnClickListener {
test = "yes!";
}
}
I have spent some hours trying to recreate your situation with different scenarios. First of all, I should point out that the life cycle of Fragments are in fact so complicated that during Google I/O 2018, one of the lead developers asked the audiences if onCreate() method of the Activity is invoked first or that of Fragment's. And the answer was that, it depends on the SDK version. But they are focusing more and more on Compatibility Libraries and advice developers to use these to have a universal experience across different devices, as well as enjoying the new APIs that will do the job of dealing with Fragments, so much easier for us.
While looking at the documentation of AppCompatActivity class, I realized that this behavior is their way of dealing with fragments.
Protected methods
void onCreate(Bundle savedInstanceState)
Perform initialization of all fragments.
void onDestroy()
Destroy all fragments.
void onPostCreate(Bundle savedInstanceState)
void onPostResume()
Dispatch onResume() to fragments.
void onSaveInstanceState(Bundle outState)
Save all appropriate fragment state.
void onStart()
Dispatch onStart() to all fragments.
void onStop()
Dispatch onStop() to all fragments.
As you can see they "save all appropriate fragment state" in onSaveInstanceState(); meaning that the states will be restored later on, after the Activity gets destroyed and recreated. So in onDestroy() all fragments get destroyed and when the Activity is created again, they get recreated as well. To make sure, you could override these methods inside both Fragment and Activity and check the result. If you do not check FragmentManager for already attached fragments, onCreate() method of the Fragment will be called twice, once directly by you -adding as a new Fragment- and once by the AppCompatActivity itself.
About the retainInstance = true, the documentation says that it keeps the member variables during configuration changes and will cause a slight difference in the life cycle of the Fragment.
setRetainInstance(true)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being re-created.
onAttach(Activity) and onActivityCreated(Bundle) will still be called.

Android: Fragment to Fragment Lifecycle

When I go from Fragment A to B, Fragment B's onResume() is called first and then Fragment A's onPause() is called. Which is different from Activity lifecycle.
How to solve this?
Check out - https://androidlearnersite.wordpress.com/2017/02/27/fragment-lifecycle-during-fragment-transaction/ ..
It explains fragment lifecycle during fragment transaction with latest appcompat version.
As per latest appcomat version, if setAllowOptimization() is set to true then during replacing fragments onResume() is called before onPause() otherwise onPause() is called before onResume().
setAllowOptimization() is used to set whether or not to allow optimization operation within and across transactions.

ViewPager and Fragment lifecycle with Activity

I'm using an Activity which has a ViewPager holding 2 fragments, the pager handler is some implementation of FragmentPagerAdapter.
As I understand, pager adapter handles the lifecycle of the fragments inside it.
I found out that my Activity onResume() method already gets called but the fragment onStart() method didn't even started.
how in the world can I fix that? it destroy the whole point of lifecycle interactions between activity an fragments...
Since pager adapter handles the lifecycle of the Fragment, does this means I can no longer depend on interaction with the Activity? I mean, if I want the Activity to do something in the onResume() but after the Fragment onStart() is called, I just can't do it...
Edited:
To make things clear:
Google says lifecycle of activity and fragment are going together, once one gets called, the other also gets called, e.g
Activiy -> onCreate() , and then, Fragment -> onCreate()
Activiy -> onResume() , and then, Fragment -> onResume()
BUT! in my case I get:
Activity -> onCreate() -> onStart() -> onResume() -> onPostResume()
And then:
Fragment -> onAttach() -> onCreateView() -> ... ->onResume().
and to be clear, I am using a pager adapter (not "state" pager) and I have an abstract base activiy in my app which all activities should extend.
public abstract class AbsLoginAppCompatActivity extends AppCompatActivity {
.............
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "*******************onCreate");
//do some general stuff like check for updates on server
}
And in my extend activity:
public class A extends AbsLoginAppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "*******************onCreate");
setContentView(R.layout.activity_a);
//also set pager + adapter + give it getSupportFragmentManager()
}
I am using:
android.support.v4.view.ViewPager
android.support.v4.app.FragmentPagerAdapter
android.support.v4.app.Fragment
android.support.v7.app.AppCompatActivity (for abs activity)
The Fragment[State]PagerAdapter uses the activities FragmentManager - or in case of a nested ViewPager in a parent fragment - that fragment's child FragmentManager to manage the fragments, just like normal fragments would do. Really, the only thing that these adapter implementations do is that they hide the nasty FragmentTransaction stuff for you.
I had never problems that particular lifecycle callbacks weren't called for me in my fragments, so I cannot say anything about that. One thing however that is important to understand and that many people get wrong is that the adapter's getItem() method is called only when a fragment is freshly created; if it is restored from a saved state this method is not called again and people tend to do all fancy things there to initialize their just "created" fragment, while they should really look into instantiateItem(), which either returns the instance you give the adapter via getItem() or returns the reference of the fragment that was automatically re-created for you.
Another thing that is good to know about fragments in pager is the method setUserVisibleHint(boolean). Since fragments are usually recreated and resumed all at once (non-state adapter) or on demand (state adapter), its usually important to know when one instance is actually visible to the user. This can be achieved by overriding the aforementioned method in a custom fragment.

Why is onAttach called before onCreate?

In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method. I can't wrap my head around this. Why would you attach a Fragment first?
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.
Because onAttach() assigns hosting activity to the Fragment. If it had been called after onCreate() then there would be no context for your fragment (getActivity() would return null) and you would not be able to do anything in onCreate() method without that context anyway.
Another fitting reason is that Fragment's lifecycle is similar to Activity's lifecycle. In Activity.onAttach() activity gets attached to its parent (a window). Similarly in Fragment.onAttach() fragment gets attached to its parent (an activity), before any other initialization is done.
This is related to retained fragments. Following Fragment setRetainInstance(boolean retain) documentation:
If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being re-created.
onAttach(Activity) and onActivityCreated(Bundle) will still be called.
Take a look at the source code (android.support.v4.app.FragmentManager, v21):
void moveToState(Fragment f,
int newState,
int transit,
int transitionStyle,
boolean keepActive) {
...
f.onAttach(mActivity);
if (!f.mCalled) {
throw new SuperNotCalledException("Fragment " + f
+ " did not call through to super.onAttach()");
}
if (f.mParentFragment == null) {
mActivity.onAttachFragment(f);
}
if (!f.mRetaining) {
f.performCreate(f.mSavedFragmentState); // <- Here onCreate() will be called
}
...
}
Example
Case 1: not retained fragment or setRetainInstanceState(false)
Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView().
onAttach() called after Activity super.onCreate() call - Activity is already initialised.
MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity#1be4f2dd
MainFragment﹕ onCreate() getActivity=com.example.MainActivity#1be4f2dd
Configuration changed. Activity recreates fragments from saved state, fragments are added/attached from inside Activity super.onCreate() call:
MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity#2443d905
MainFragment﹕ onCreate() getActivity=com.example.MainActivity#2443d905
MainActivity﹕ super.onCreate() returned
Case 2: setRetainsInstanceState(true)
Application is started. Fragment is added dynamically using FragmentManager or inflated from XML via setContentView(). Same as above:
onAttach() called after Activity super.onCreate() call - Activity is already initialised.
MainActivity﹕ call super.onCreate() before
MainActivity﹕ super.onCreate() returned
MainFragment﹕ onAttach() getActivity=com.example.MainActivity#3d54a168
MainFragment﹕ onCreate() getActivity=com.example.MainActivity#3d54a168
Configuration changed.
Fragment onCreate() not called, but onAttach() still called - you need to know, that hosting Activity has changed. But still fragment is already created, so no onCreate() called.
MainActivity﹕ call super.onCreate() before
MainFragment﹕ onAttach() getActivity=com.example.MainActivity#d7b283e
MainActivity﹕ super.onCreate() returned
Two Points from Android developer Site hints at why onAttach() is called before onCreate() in case of Fragment Life cycle.
A fragment must always be embedded in an activity. Now this means for Fragment to EXIST, there has to be a "living" Activity.
Also, When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy.
So Fragment must FIRST "attach" itself to activity to defines its own view layout
onCreateis Called to do initial creation of a fragment.
It is obvious that you will create something only when its pre-condition of creation is in place (and the pre-condition is A fragment must always be embedded in an activity, and it must be attached to its Activity)

Categories

Resources