10 December 2010

Quick tip: Quick Formatting of Android XML Files

One of the most useful tools in Android's Eclipse plug-in is the Layout Editor. It is easy to experiment with layouts using the drag-and-drop enabled editor without having to worry about the correct syntax or if you are using the correct attribute name.

After creating your layout this way, however, you can end up with a messy XML file. I say "messy" in the sense that elements can run on in one veeeeeeeeeeeery long line, and if you are about to edit the XML file manually, this can be a nightmare.

I used to format the XML file by hand, putting in line breaks and correcting indentation. But one edit using the graphical layout editor and it's messed up again. And then I had a light bulb moment. Eclipse allows auto-formatting of code, but what about XML files? AHA!

It turns out that auto-formatting works for XML files too! Simply select all the contents of the XML file (CTRL-A) and then press the ultra magical shortcut CTRL-I and your XML file is clean and orderly as can be! YAY!

What happened to my layout editor?

There you are, happily creating your layout files in the Eclipse plug-in's layout editor. Dragging and dropping is a breeze. But then one day, you open a layout XML file and boom! No UI! All you see is the XML tree with all the nodes and attributes. What happened?

This happened to me and I was in a panic for a few seconds. Why do things like these have to happen to me? I tried opening a layout file from another project in the same workspace, and it has the UI! What happened?

It probably has something to do with the interpreter you used to open the XML file, a voice in my head said. So I tried right-clicking on the XML file, and lo and behold, I found it. I may have accidentally clicked on some file in one of my mad-clicking moments and changed the setting.

So anyway, to bring back the Layout UI Editor, right click on an XML file > Choose Open With > Android Layout Editor.

I would say that everything is handy dandy, but apparently, the engineers at Google decided that we developers need a little less help and removed the very useful up and down arrow keys in the Outline View when editing XML layouts. Why do they hurt us like this?