Kotlin's simple layout trick (part 1)
When developing Android applications, I create my layouts in XML. Despite the preview mode there is not much that I like about it: All the properties are prefixed with android:
(which doesn't promote readability), the files are lengthy and… it is not code!
When moving from XML to Kotlin, the first thing we can apply is Anko Layouts: A fast and type-safe way to write dynamic Android layouts. Although this is a great alternative for XML, it has some drawbacks:
- It is hard to extent.
- It does not distinguish between creating a view and adding it to the layout.
- It is a complex library for the simple thing we want to achieve.
This sounds negative, but there is a lot to love about Anko Layouts and actually the whole Anko family. So don't feel discouraged in using it. Yet having a library for everything quickly enlarges your APK size and leaves you, the developer, without knowledge and control.
Enough introduction, let's write some code! The first achievement we will be creating is a layout and we will add some views to it through code.
Within this code there are some things that could be prettier:
- The
addview
method is trivial. - Same for the
apply
function - Within the LinearLayout, creating children should be easier.
We only want this functionality for a Viewgroup
so we will create a DSL for it.
Within the layout class we can add the utility we need. Lets start with replacing the addView
method with a unaryPlus
operator function.
Next we want to avoid to call apply
every time to we need to initialize the child view.
Our last point is adding utility for quickly creating new views. This can be accomplished by creating extension properties.
Thats it! In about 20 lines of code we created a Kotlin DSL that simplifies the layout creation and grants us access to all the goodness Kotlin is supplying. If you liked this article, please give it some claps. If you have any tips or questions, please file an issue on the repo: https://github.com/Lamartio/Kotlin-s-simple-layout-trick.