Wednesday, October 16, 2013

Xtend & Android - Sneak Preview

In preparation of upcoming presentations for EclipseCon and W-JAX on that matter, I dived deeper into Android development and worked improving common programming idioms in that area. I'm contributing to Toby Kurien's Xtendroid and in this post I want to give you an idea of how Xtend can help developing Android applications.

Binding Android Layouts to Code

In Android user interfaces are mostly developed using Android's XML format for layouts. You can program them using Java but that's not what people do most of the time for various reasons. One of course being the verbosity of Java, but also the tools around the layout XML are quite helpful, especially when you have to deal with internationalization and need to support a wide range of devices.

Of course XML alone doesn't cut it which is why you have to bind the stuff declared in XML to Java code somehow in order to add listeners and other dynamic functionality. By default this is quite cumbersome as you have to deal with untyped code (cast) and a lot of integer constants. Some thirdparty frameworks try to reduce this problem by "injecting" the needed views reflectively, but that doesn't really help much. It's still not type safe and therefore error prone and you'll have to redeclare (i.e. duplicate) what you have declared in XML already.

With Xtend you can use an active annotation, which just points to the xml layout file. An active annoation is a macro annotation, which allows for participating in the compilation. This one will look into the referenced layout XML and declare local fields for any elements attributed with an '@id'. It also will derive an interface with all onclick methods declared in XML and make the current class implement it. As a result there is zero duplication and 100% type safety. The best is that the IDE knows about the changes and provides you with respective compilation problems, quick fixes, content assist and also the outline shows what has been derived from the XML layout file.

This is best shown in a small demo:

Xtend and Android - Binding XML Layout and Code from Xtext Team on Vimeo.