Kotlin's simple layout trick (part 1)

Danny Lamarti
2 min readSep 10, 2018

--

“turned on Android smartphone” by Pathum Danthanarayana on Unsplash

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.

The initial layout has no syntactic-sugar for creating readable layouts.

Within this code there are some things that could be prettier:

  1. The addviewmethod is trivial.
  2. Same for the apply function
  3. Within the LinearLayout, creating children should be easier.

We only want this functionality for a Viewgroup so we will create a DSL for it.

Creating the DSL.

Within the layout class we can add the utility we need. Lets start with replacing the addView method with a unaryPlus operator function.

The operator function enables us to write simplified syntax.

Next we want to avoid to call apply every time to we need to initialize the child view.

The generic invoke is in functionality the same as calling .apply()

Our last point is adding utility for quickly creating new views. This can be accomplished by creating extension properties.

Creating extension properties will simplify layout creation.

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.

--

--