How Android Layouts Become Programmable View Objects
During layout inflation, our XML layout designs become living, breathing in-app View objects. This process, largely handled by a single method in the Activity class, enables us to manipulate Views in code after rendering them on-screen.
setContentView performs this daunting task, and thereafter, findViewById permits us to recover individual on-screen Views and ViewGroups by their resource identifiers. This one-two punch is what developers use to populate their interfaces with meaningful data and imagery.
To recover a View in code, we invoke findViewById like so:
// We must invoke setContentView before invoking findViewById
View userName = findViewById(R.id.tv_netflix_userName);
To access class-specific methods, we change the type from the default View to the specific type of View or ViewGroup as defined by our layout file:
The setContentView method begins the layout inflation process and presents the final, programmatic version of our layout as on-screen content.
The static R class exposes all available resource identifiers through R.id.<id_name>.
Activity objects may opt to present nothing to the screen, but the Android operating system always provides them with a Decor View.
The Decor View is the top-level ViewGroup in which an Activity may place its visible content.
After setContentView returns, we may use the findViewById to recover the programmatic View objects that represent our on-screen content.
Unless modified, findViewById returns the base View type, however, we often require the exact type to access class-specific methods, such as setText on TextView and setImageResource for ImageView
“Hardcoding” is the practice of programming with constant values that we should otherwise pull from more meaningful sources, e.g. “I hardcoded the user’s first name and email, but, in production, we should pull that data from the server.”
Include components are not ViewGroups.
We may use Log.d to post messages to logcat (system logs) and quickly verify assumptions about our code.