DEMO 03

Views and ViewGroups

An XML layout is not a picture — it is a tree of objects. Click any node and see what class it really is, and what that class can do.

What to do

Click from the top down. The Activity is not a view at all; the DecorView is added by the framework, not by you; everything you wrote lives below that.

Then askWhich of these classes can contain another one?

Turn on Only ViewGroups to see the answer highlighted — those are the only nodes with children.

activity_stopwatch.xml → the live tree

One class to rule them all

Every widget and every layout descends from the same class. That is why they can all be styled, positioned, hidden and listened to the same way.

Say this out loud“A layout is a view that holds views.”
The inheritance chain that matters
java.lang.Object
   └── android.view.View              // one thing on screen
          └── android.view.ViewGroup   // a View that can hold Views
                 ├── LinearLayout
                 ├── FrameLayout
                 ├── RelativeLayout
                 └── ConstraintLayout
          └── android.widget.TextView  // note: this one is NOT a ViewGroup
                 └── android.widget.Button   // a Button IS a TextView

View

one rectangle on screen

Knows its size and position, can be drawn, can be clicked, can be shown or hidden. A TextView, a Button, an ImageView — all Views.

ViewGroup

a View that contains Views

It has all the abilities of a View plus the job of measuring and positioning its children. Every layout in Android is a subclass of it.

White storage boxes nested one inside another

Photo Castorly Stock · Pexels #3912293 · a ViewGroup is a box that holds other boxes — and those boxes can hold boxes.

Because a deep tree is walked every single frame.

When Android draws the screen it walks the whole tree — measuring, then positioning, then drawing each node. A tree that is ten levels deep costs far more than one that is three levels deep, and it happens on every frame.

This is the whole reason ConstraintLayout exists: it lets you flatten a nest of nested layouts into one level. The rule of thumb for the rest of the semester: nest only when you cannot express the same result any other way.

In the tree on this page, count the depth of start_button — four levels below the Activity. Every one of those levels is doing work that a flatter layout would not need.