What is the difference between OnCreate and OnCreateView in the lifecycle of fragments. Also why there is no OnCreateView in Activity life cycle but in frgaments. I am confusion in these two methods.
Please help me with the suggestion as I am very new to android programming.
onCreateView() allows you to inflate a layout for a fragment and get your views with findViewById().
The fragment's onCreate() gets always called directly before the onCreateView() method. It does not allow you to setup a fragment layout, so you always have to override onCreateView().
Most times you do not need the fragment's onCreate().
An activity does not need onCreateView(), since it has the setContentView() method, which allows you to setup a layout in the activity's onCreate().
This question is not about how to detect if a view is attached or detached.
In general, when is a view attached or detached? Is there a lifecycle diagram for this?
To clarify, I'm looking for answers to what happens when: Activity sent to background, opaque view placed on top, visibility set to GONE, view inflated, parent detached, etc. This is not an exhaustive list - I just want to understand how attaching and detaching of views works, at a fundamental level.
Update with more examples of what I'm trying to get at:
What about fragments vs. activities?
What about nested views - in what order are views attached/detached (parent->child or child->parent)?
Are views measured before they are attached or after?
What about using addView() to a ViewGroup manually?
Edit: Summary:
For Activities, views are attached in setContentView(). Views are detached in onDestroy() or when setContentView() is called with a different view.
For Fragments, views are attached after onViewCreated() finishes, and are detached after onDestroyView() finishes.
For ViewGroups, views are attached in addView() and detached in removeView()
setVisibility() does not affect the attached state of a view
From the official documentation:
An activity is a single, focused thing that the user can do. Almost
all activities interact with the user...
The first thing that needs to be noted is that it is not a must for activities to be associated with a layout. You can have an activity with no UI (and hence no View). Android even specifies a no UI theme for this.
Moving on to your question - a View gets attached to an Activity at the moment you call setContentView(view). This is usually called within the onCreate() method. The reason you usually have this in the onCreate() method is because most of the initialization is done there. And how could you initialize your widgets if the view has not been inflated and attached to the Activity? Hence, if you have a view, you almost invariable end up calling setContentView() inside your onCreate() method preceding all other initialization.
But does that mean that the view (if it exists) must be tied to the
activity only within the onCreate() method?
To answer this question, let's see what the lifecycle of an Activity looks like. You start your app:
onCreate() -> onStart() -> onResume() // They get called consecutively
The stage you are now in is where all the widgets have been initialized.
So why not inflate and attach the activity in onResume() and do all the
initializations there?
Of course, you could. But imagine what happens when a dialog (a partially opaque view) shows up? The Activity is now partially covered and is in the background. The onPause() method is called. The layout is still attached to the Activity at this point. You take some action and dismiss the dialog. onResume() gets called. The layout would be inflated again. All the initializations would happen again and you would lose your state. Even if you did not have much in the way of initialization, you would still be making a pretty expensive call by calling onCreate() again. And you want to avoid this in resource limited mobile devices.
What happens when an opaque view comes up and the Activity is now in
the background but still running (like an incoming phone call or opening another activity)?
Now the following callbacks happen:
onPause() -> onStop()
When you move back to the original activity
onRestart() -> onStart() -> onResume()
For the same reason as I mentioned in onPause() you do not want to inflate and attach a layout here.
But what happens to the layout itself when an Activity is in the
background. Is the layout still attached?
Yes, it very much is. If another activity comes up which uses the same layout as the original activity, then the new activity has it's own layout and there is no sharing of layouts.
What happens if the user terminates the activity by pressing the Back
button?
Assuming the onBackPressed() method is not overridden to achieve custom behavior (in which case, it is up for grabs), onDestroy() is called and the activity is destroyed and there is no View associated with it anymore.
What happens when the activity is in the background and the Android GC
decides to destroy the activity and reclaim resources?
According to the activity lifecycle within the documentation, onDestroy() will be called. But there is no guarantee of this. At this point, the activity and it's associated view are simply garbage collected and there is no connection.The next time you start the app, onCreate() will be called as usual and you simply start from the beginning again.
What happens when I rotate my device?
The way Android works is to actually destroy the current activity and inflate the new layout again and start from the onCreate() method again. So what technically happens is:
onPause() -> onStop() -> onDestroy() -> onCreate() -> onStart() ->
onResume()
Because of this, you can even have a different layout and view while in landscape mode.
EDIT: Added the relationship between activities, fragments and views
A fragment represents a portion (or behavior) on the screen. A fragment can be made to occupy the full screen or you can have multiple fragments within an Activity. Fragments have their own life cycle but it is closely tied to the host activity's life cycle (and beyond the scope of this answer). Since we are specifically talking about views, I will limit this answer to two methods of interest:
onCreateView()
onViewCreated()
The methods are called in the following order:
onAttach() -> onCreate() -> onCreateView() -> onViewCreated()
You do the actual layout inflation within the onCreateView() and then you do the initializations within the onViewCreated() method. The result of the onCreateView() method is used by Android to inflate the view.
So when is the fragment created in the first place by the Activity?
There are two ways to display fragments - one is to put them within the xml layout of the activity (just like any regular widget where instead of the widget name, you will be using the fully qualified package name of the fragment class) or you can do the addition using FragmentManager programmatically (which is the preferred method).
If you were defining the fragment within the xml layout, you should know that the fragment cannot be removed programmatically. It would be hard to modify this and reuse that screen space for other fragments. Also in this case, the view is attached and tied to the activity. In this case, you will inflate the xml layout of the Activity within the onCreate() method of the activity. So now, the flow will looks something like:
onCreate() [Activity] -> onAttach() [Fragment] -> onCreate()
[Fragment] -> onCreateView() [Fragment] -> onViewCreated() [Fragment]
-> onStart() [Activity] -> onResume() [Activity] -> onActivityCreated() [Fragment]
So first the fragment view is instantiated and attached to the fragment before the onStart() method of the activity is created.
If the fragment is added programmatically, if it is added within the onCreate() method, then it follows the same flow. It can be started anywhere. You simply have to substitute the life cycle of the fragment within the activity in the appropriate place. When you add fragments programmatically, while the fragment is hosted in the activity, the view is attached to the activity. When the fragment is removed from the activity, onDetach() is called and the view is no longer a part of the Activity. The resources taken by the fragment can be released.
What about Nested Views, Nested Fragments, etc.?
In nested views, like one layout container inside another, the rules of the parent container apply to the immediate child container. Always the parent gets initialized first. So for a widget inside a LinearLayout, the parent LinearLayout is constructed first immediately followed by the child. When destroying such views, everything goes when the parent ceases to exist. I have not read about any documentation as to an order in which this may happen. The Android GC may have rules but I am not sure if they are documented anywhere.
You can have nested fragments too - in this case, the parent fragment gets initialized before the child fragment does (and it makes sense doesn't it?). When a parent fragment ceases to exist, the child will also cease to exist. The child cannot exist without the parent but you can have the parent without the child.
The bottom line for nested views is that once the parent view is
destroyed, it takes the child view immediately with it.
Are views measured before they are attached or after?
Views are measure after they are attached. Calling getMeausredWidth() or getMeasuredHeight() will return zero prior to this. But what you can do is call neasure() directly on the view before it is attached and pass MeasureSpecs (I would suggest you read up more on this in the official docs) to set some constraints. But this option is not fool proof as it depends on the parent ViewGroup enforcing it's own constraints which take higher precedence. To simply answer your question, views are measured after they are attached.
What about using addView() to add a view to a ViewGroup manually?
This is simply the same as nested views. The child exist only when they are added and this is controlled by the user. In nested views defined in layout xml, the children are inflated immediately after their parent. Here the control is more in the hands of the user. When the parent view in this case is destroyed, it takes the child view with it.
As a last point, I'd also like to mention that you should not use static handles for views as this would lead to a lot of headaches with the tearing down of views.
I have read several documents about this but still fail to conclude where should I write my codes to set some values in textviews/edittext ...
what i have read and seen in video tutorials is, both onStart and onActivityCreated methods get called with different actions (like after fragment initiated, or orientation changed etc.). Moreover, both of them get called after Activity's onCreate method, which means views are available from both Fragment methods.
Anybody can give me some advise regarding this?
(p.s. Currently I put all codes accessing xml views inside onStart, and my application is running without any issue)
I don't know of any potential problems with accessing your layout's views in onStart or onActivityCreated.
Personally, I usually set references to my layout's views and set initial values in a fragment's #onViewCreated(). This is the first opportunity after the layout has been inflated that you have to access a layout's children. The View that was inflated is passed as a parameter so you even have direct access to the parent layout object if you needed it for some reason.
According to the fragment lifecycle onActivityCreated() will be called next and then onStart(). All of these will be executed in that same order when a fragment is returned from the back stack -- so it seems to be personal preference.
I am working on a application for which I have some issues with fragments. First of all , I want to know if it is possible to make one fragment inside another fragment. And the second one is when to call onCreateView() and onActivityCreated() and which is best?
Per the Android sources:
onCreateView is called by the Activity during the construction of the view hierarchy. This is where the Fragment has the opportunity to instantiate its own user interface view.
onActivityCreated is called when the Activity has been fully created and finished instantiating the view hierarchy. At this point it's safe for the Fragment to access the its views and restore itself from some saved state.
You cannot create a fragment inside another fragment. You should communicate between fragments thru activity.See http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
I didn't understand your second question clearly. But I generally leave onActivityCreated() blank without changing it. And use onCreateView() in a similar way with onCreate().
I'd like to show and hide ViewPager on particular occassions, however this ViewPager element holds quite a bit of Bitmaps that should be recycled. When I do setVisibility(GONE) on VierPager it doesn't trigger any of the callbacks related to its' pages.
Is there any system way to tell ViewPager to destroy view of all the pages it hosts ? I think I could wright somewhat like:
foreach(page from viewPagerPages) {
page.onPause();
page.onStop();
page.onDestroyView();
}
but I'm not sure about it.
Thanks.
To destroy Views use ViewPager's method removeAllViews (). It is inherited from ViewGroup.
removeAllViews () - Call this method to remove all child views from the ViewGroup.
Here a lot of different methods to manipulate ViewPager.