When are views attached and detached?

William picture William · Mar 12, 2015 · Viewed 13.2k times · Source

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

Answer

ucsunil picture ucsunil · Apr 7, 2015

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.