Android Studio: The best way to easily declare your UI properties from XML
I recently started studying Android development(I am specialized in iOS) and so far I learned the patterns to handle UI and layout in the XML file in a way it may be referenced in your AppActivity
class. It's someway very similar to what we already do in iOS with the IBOutlets
, which are variables that correspond to some UI element in your Interface builder(Storyboards or xib files). In the materials I was looking at, it's very common to just instantiate your View properties using findById
function and reference it just inside the scopes its used:
Some people also rely on a better approach by declaring a nullable property for the element and initializing later on:
The problem is that we are just initializing our TextView
later in the activity lifecycle and we need to deal with a nullable type, not being able to be certain manipulating it will have effect in our layout, without even considering we need to unwrap its properties any time we need.
Some people like lateinit
to work with unwrapped values, but it may cause crashes if not well implemented. We need a way of having access to our UI elemenst without the risk of being null and have it initialize by the time we need.
Lazy evaluation
Lazy evaluation is a way of guaranteeing we will only run the initialization block of our variable when we access it. By doing that, we have all our UI elements configured when we need and we don't need to initialize it by the beginning of the activity lifecycle. Therefore, we are not working with nullables anymore:
Great, now we are initializing our UI properties by accessing its id in our XML file:
The greatest part of it is that we can apply some configuration to the new element without the need of doing that in the XML itself. This way we can achieve something closer to what we usually do in iOS with ViewCode:
Now we are initializing each UI element of our XML in a lazy way and assigning some properties to it before actually using it, like listeners and text values.
Conclusion
In this article we demonstrated a way of handling UI variables in our Android Activity
without the need of keeping them nullable and also initializing their properties without relying exclusively in the Interface Builder(XML). This way decreases a lot the coupling we previously had with the XML file and became closer to the ViewCode pattern we usually apply on iOS projects. I hope you enjoyed ;).