Android code generation

I started looking more seriously into Android development, especially after a great training session with Mark Murphy organized by Chicago Android. Right now I am experimenting with simple user interfaces (buttons, lists, etc) and learning how to utilize various phone’s sensors.

What’s caught my attention is the way Android’s build tools generate code. The layout for activities, templates, styles and controls is defined in XML files. These are then parsed at build time to extract the IDs, which then become available off the generated “R” class. The layout is “inflated” at runtime given a numeric ID. That’s also how one can get a reference to UI elements.

The use of XML files for UI layout is not unique to Android. In the past I used Glade, Mozilla’s XUL and Microsoft’s XAML. Lately especially I’ve been playing XAML. It was a surprise to me that pretty much every single Java sample contains code like this:

Seems very repetitive and a lot of silly code to write. Tooling for other frameworks take slightly different approaches. In XAML there is a special namespace used by the XAML parser that allows the user to specify a name for the class member referencing the layout element. For example:

results in creation of member variable “ClearButton” in the class “MyCoolWindow” of “MySample” namespace. No need for getting view elements by id and for casting. I’m wondering why can’t something like this be done for Android?

I obviously am not even pretending to know anything Android, so I am asking you the experts =)
Is there any technical reason against it?

C# has a concept of partial classes (one class spanning multiple source files), so it’s easy to just stick the generated code into its own file. Java’s philosophy is different: why span multiple files? Just create multiple classes. Seems like it shouldn’t be that difficult.

One could come up with an XML schema for specifying the name (like in XAML). XML allows decorating elements with multiple attributes, so it would work. Or, alternatively, the name specified in android:id could be used, but I think it needs to be unique for all IDs. Specifying a name per class could be more desirable.
Please see a mockup file below:

A custom pre-processor tool could be written that would parse the XML files and create a new class for each of them – say “LayoutXyzHelper”. These helpers would perform all the findViewById() during construction and expose all desired controls as member variables. A generated helper class for the XML layout above could look like this:

The usage would be to construct the layout helper and save it as a “ui” member variable.

Well, what do you think? Does this sound like a good open-source project idea? Or am I missing something obvious due to my lack of Android experience? Maybe this has already been done?
Either case, please let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *