Creating UI widgets from pure Kotlin without XML
We can also create widgets from Kotlin objects that are not a reference to an object in our layout. We can declare, instantiate, and set a widget's attributes, all in code, as follows:
Val myButton = Button()
The preceding code creates a new Button
instance. The only caveat is that the Button
instance must be part of a layout before it can be seen by the user. So, we can either get a reference to a layout element from our XML layout in the same way that we previously did using the findViewById
function, or we can create a new one in code.
If we assume that we have a LinearLayout
in our XML with an id
property equal to linearLayout1
, we can incorporate our Button
instance from the preceding line of code in it, as follows:
// Get a reference to the LinearLayout val linearLayout = findViewById<LinearLayout>(R.id.linearLayout) // Add our Button to it linearLayout.addView(myButton)
We can even create an entire layout in pure Kotlin code by...