Declaring and initializing the objects from the layout
We know that when we call setContentView
in the onCreate
function, Android inflates all the widgets and layouts, and turns them into real instances on the Heap.
We know that to use a widget from the Heap, we must have an object of the correct type by using its unique id
property. Sometimes, we must specifically obtain a widget from a layout. For example, to get a reference to a TextView
class with an id
property of txtTitle
and assign it to a new object called myTextView
, we can do the following:
// Grab a reference to an object on the Heap val myTextView = findViewById<TextView>(R.id.txtTitle)
The left-hand side of the declaration of the myTextView
instance should look familiar to all the instances of other classes that we declared throughout the previous three chapters. What is new here is that we are relying on the return value of a function to supply the instance. The findViewById
function does indeed return an instance that...