Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton