Using Android Styles with Anko

Jonathan Rafael Zanella
AndroidPub
Published in
2 min readApr 16, 2017

I always liked to use android styles to help me organise my screen layout.

I used to create styles where each one define elements, like a style for the main layout of each view, another for statics, another for edits and etc.

Since I don't have any design skill, creating the screens thinking in those elements helped me to keep a minimum of standard in my apps.

For example, the main layout of the screen is something like that:

And the utilization of the style:

Recently I decided to rewrite my app in Kotlin and convert my layouts to use the Anko library.

The same layout using anko DSL:

I run my app I realised that my style is not being applied, more precisely the margin attribute.

I posted a question at stack overflow and received as answer that the way Android treat layout_* attributes inside styles did not make possible to achieve the behavior I was expecting.

I did not understand 100% of the issue, but I understood that the way I was working with styles would not work. If you want more details, check the question.

With this I started to look for alternative ways to get the same behavior that I had before Anko.

During my research I saw that Anko has support to execute a function after layout generation where you receive each view of the layout and can apply styles.

With this I wrote the following function:

And call it in the layout definition:

With this I am able to apply the styles that I want, but I would apply the styles to all RelativeLayouts on the screen and not only for the one I want.

To avoid this problem I decided to create a class that extend RelativeLayout and I can use it to put in my layout and apply the style only for it.

And to keep compatible with Anko's DSL, I created a function to create a view of the type ViewFrame

With this I only need to update the function applyTemplateViewStyles with the new type:

And update the layout with the new type:

With this approach I got a behavior very similar that I had, the only negative side is that before I could redefine the attributes inside the tag view and now it is not possible anymore. This happens because the styles are only applied after the view definition.

Despite the negative side, I think that migrating to Anko bring a lot of benefits, the DSL allows to define the screen layout with less code and you keep the layout definition in the same file of the screen class, what helps a lot during the code maintenance.

Thanks for Gustavo Freitas for the review.

--

--

Jonathan Rafael Zanella
AndroidPub

Android Developer at HE:labs. I like mobile stuff, specially android and kotlin.