I see from Android Developers (http://developer.android.com/reference/android/app/Activity.html) that there is a nice flowchart showing onCreate leading to onStart then to onResume, and so forth. My question is: what other on****() methods appear in between onCreate and onStart?
For example, I've been doing research on the topic, and I know other methods such as onMeasure and onSizeChanged, onDraw, and others exists. Where do they fit in to that flow chart?
Thank you.
The methods you mentioned aren't related to the Activity lifecycle.
For instance, it would be incorrect to include the call to onMeasure in the Activity lifecycle flow chart. onMeasure is called whenever the layout changes (i.e. when requestLayout is called) or the first time a window is laid out. The call to onMeasure isn't directly related to the system's calls to onCreate and onStart.
Those other methods exist, but they don't really fit in any one place on that flowchart, nor are they part of the activity lifecycle. in fact, that's why they're not on the chart. The ones you mentioned are really more of the view lifecycle which is separate from (though admittedly related to) the activity lifecycle.
This image can clearly depict what you want.
Related
I am utilizing a FragmentPagerAdapter to manage a ViewPager with 4 tabs, I'm also utilizing EventBus to monitor changes between tabs. These tabs are all related in the fact that they can add content which should update in another tab.
The way FragmentPagerAdapter works is upon a swipe to another tab, it CAN destroy the view of the previous tab (onDestroyView() seems to be called every single time the Adapter must release memory), however, it often does not destroy the view, it only pauses the fragment.
This being said, I am using an MVP design and I am currently binding the EventBus in onViewCreated() to the Presenter and then unbinding it in onDestroyView(). This allows for events from another tab to reflect instantly in preceding tabs that have been swiped away (so long as the Fragment's views exist still). This removes the necessity to use Sticky events and manage them appropriately.
If the Fragment's views are actually destroyed, when the user navigates back to the Fragment it's onViewCreated() methods will fire redrawing the entire Fragment's views from the most recent data. So both situations are covered efficiently, the situation where a view still exists (and it gets updated), as well as the situation where there is no view, and a new view must be drawn.
Therefore, I don't see any holes in my plan, however, I have NEVER seen this approach discussed. Is there a really bad reason I should not be doing this? Or is this just a good solution for a very specific design?
Your expertise is appreciated!
I have done similar things before. It's common practice to use an event bus along with the lifecycle of views in order to best manage their display when it's relevant to do so. The problem is registering a listener before the view is actually available, and unregistering after it's no longer going to be used, which is sounds like you are not doing.
BTW, for anyone reading this, there are different practices for different situations. For Activity instances it is common to use onStart and onStop to register and unregister the listener, but you still have to understand the flow of events through your bus to see if it still makes sense.
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 making an app with multiple tabs (without the tabview). One takes a long time to load so I made a singletask of it. Now it only has to load once what saves a lot of time.
Only in the onCreate I define the transition I want:
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Only the onCreate is never called again, i tried to put it on top of the onResume and onStart but that didn't helped either.
The problem now is that the animation becomes the default animation which differs a lot on different devices.
Does anyone know a way to change this? I tried calling it after the startActivity method with no succes either.
If anyone has a solution to stop the loadtime then it is also okey.
The load time goes to making multiple listview in a swipeview (jason fry). This listview contains around 90 imageviews each, most of them are the same image.
Thanks for any thoughts, ideas or solutions in advance.
You should override the finish() method of your activity.
In the overridden method, after calling super.finish() - call overridePendingTransition() with your favorite transition (if you want no transition - define a transition that does nothing, with duration 0).
You could try calling that in the onNewIntent() method. That should be called when you try to launch the Activity a second time.
In my application we are achieving the page-animation by using setContentView every time the animation occurs. The layout contains just an image so its definitely not too heavy. But are there any other problems in calling setContentView again and again on the same activity. Will it cause memory leaks or something similar.
Tried searching the net but since our layouts contain only the imageviews the onSaveInstance also doesn't have much to do.
Let me know your inputs.
PS I know about ViewFlippers and other waqys of animation. Was just curious if its advisable not to call setContentView in an activity repeatedly and Why?
And I can't create a tag for setContentView if any of you can please tag this question with that tag.