Android Programming In Kotlin: Layouts and Autonaming Components
Written by Mike James   
Wednesday, 27 December 2017
Article Index
Android Programming In Kotlin: Layouts and Autonaming Components
Finding View Objects

Finding View objects

One problem we have to solve if you want to work with the View hierarchy created by an inflater is finding View objects in the hierarchy. In the example where we built the View hierarchy in code it was easy to keep track of a button or a textView by simply keeping a reference to when it was created.

An inflater simply returns the View hierarchy without an easy way to get at a particular object, a button say. One way of solving the problem would be to "walk" the View tree. A ViewGroup object, e.g. a Layout, not only has an addView method but also a range of methods that allow you to access the objects it contains. Each child object is assigned an integer index – think of it like an array. The method:

getChildAt(i)

will return the child object at index i. You can also use:

getChildCount()

to find out how many child objects are stored in the container. 

Using these methods you can search the hierarchy for the View object you want but how do you know which one it is? The answer is that all View objects have an id property which should identify them uniquely. The id property is set as part of the XML file.

To avoid you having to work out an id value, the standard way of setting an id is to define a resource within the XML file:

 <Button
     android:id="@+id/my_button"

When the XML file is inflated the @+ symbol is interpreted as "create a resource". An integer id is generated using the generateViewId method and this is used to both create the id property and to add a my_button property to the id property of the R object, R.id.

If you are using Kotlin to work with the XML file it automatically converts all of the string labels on the ids to Activity properties and then makes them reference the objects that the inflater creates. To allow this to happen you have to enable the kotin-android-extensions plugin – which is enabled by default in a Kotlin project. You can then specify which layout files you want to create properties for using:

import kotlinx.android.synthetic.main.layout.*

So to import properties for all of the View created by the two standard XML files main.activity_main.xml and main.content_main.xml you would use:

import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.*

These are automatically added to your project file when it is created. To import them simply start typing the id of any component and then accept the prompt to import the "synthetic" files. Any other layout resource files that you create will also be added automatically so that their ids are properties also.

The only minor complication is that when you set an id using the Layout Editor it will auto generate the @+id/ for you. So in the Attributes window you will see my_button not @+id/my_button which is what is entered into the XML file. This is helpful, but it can be confusing.

There is a lot more to say about resources, but for the moment this is enough to understand what is going on. Resources deserve a chapter all to themselves and you’ll come to it after we’ve looked at menus.

What all this means is that not only do you get an autogenerated id value, but also a way to get this value into running code. You could use the getChildAt methods to step through all of the View objects in the hierarchy, but it is much easier to use:

findViewById<Button>(R.id.my_button)

which returns the object in one instruction. If you are not using Kotlin’s conversion of ids to properties then this is the only sensible way to work and Java programmers make use of the findViewById before they can work with any View object in code.

The general method, in Kotlin, is to inflate the XML, set it as the content of the View, and use the generated Activity properties to work with any View object you want to.

What all this means is that in most cases there is no need to do:

val button=findViewById<Button>(R.id.button)
button.text="my button"

as button already exists as a property. You can simply write:

button.text="my button"

 

This is just one of the ways in which Kotlin makes Android programming much easier than its Java counterpart.

 

kotlinlogo

Summary

 

  • All of the UI components are derived from the View class.

  • An Activity can host and display a single instance of the View class set by one of its setContentView methods.

  • You can create instances of View objects in code and set them to be displayed by the Activity.

  • A Layout or ViewGroup object is a View object that can contain many View objects, so creating a sophisticated layout that the Activity can display.

  • You can also code the View hierarchy using XML. Each XML tag corresponds to a View object and they are nested to define the hierarchy. The properties of the objects are set within the XML as attributes. Layout properties are treated in the same way but with layout_ as a prefix.

  • When the time comes for the View hierarchy to be assigned to the Activity, the XML file is converted into a nested set of View objects by the use of an inflater method. This simply reads the XML and converts each tag to an object and sets the object’s properties.

  • To find particular View objects in an inflated hierarchy the usual approach in Kotlin is to generate properties corresponding to the ids. If you don’t want to do this then you have to use use the findViewById method. 

 

Android Programming In Kotlin
Starting with an App

Covers Android Studio 3 and Constraint Layout.

Is now available as a print book:

coverKotlinsmall

Buy from: Amazon

Contents

  1. Getting Started With Android Studio 3
  2. The Activity And The UI
        Extract: Activity & UI  
  3. Building The UI and a Calculator App
        Extract: A First App
  4. Android Events
  5. Basic Controls
        Extract Basic Controls
        Extract More Controls ***NEW!
  6. Layout Containers
        Extract Layouts - LinearLayout
  7. The ConstraintLayout 
        Extract Bias & Chains
  8. Programming The UI
        Extract Programming the UI
        Extract Layouts and Autonaming Components
  9. Menus & The Action Bar
  10. Menus, Context & Popup
  11. Resources
        Extract Conditional Resources
  12. Beginning Bitmap Graphics
        Extract Animation
  13. Staying Alive! Lifecycle & State
        Extract  State Managment
  14. Spinners
  15. Pickers
  16. ListView And Adapters
  17. Android The Kotlin Way

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Wednesday, 27 December 2017 )