Programming View Objects
Learn 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 setContentView(R.layout.netflix); 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:
//View userName = findViewById(R.id.tv_netflix_userName); TextView userName = findViewById(R.id.tv_netflix_userName); userName.setText(user.userName);
setContentViewmethod begins the layout inflation process and presents the final, programmatic version of our layout as on-screen content.
- The static
Rclass exposes all available resource identifiers through
- 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.
setContentViewreturns, we may use the
findViewByIdto recover the programmatic View objects that represent our on-screen content.
- Unless modified,
findViewByIdreturns the base
Viewtype, however, we often require the exact type to access class-specific methods, such as
setTexton TextView and
- “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.dto post messages to logcat (system logs) and quickly verify assumptions about our code.