Auto Formatting Android XML Files With Eclipse

http://www.androidpolice.com/2009/11/04/auto-formatting-android-xml-files-with-eclipse/

http://envyandroid.com/archives/195/formatting-android-xml-eclipse

The Problem

However, one thing about Eclipse Android development has bothered me for a while - and that is XML formatting by the visual tools. See, if you open an XML file in Eclipse and use the Layout/Resources tab (which functions as either a visual UI builder or a visual frontend to resource management), Eclipse creates the XML representation of what you're building and dumps it into the file you're editing. The problem is, this XML is not formatted in any way - Eclipse just writes it in a single line, which looks absolutely horrible and is essentially unusable.

For example, I had this beautifully formatted XML file with a sample Android menu. After using the Layout tab to add another item, I ended up with an single ugly unindented line for it.

image

The Solution

Here's how to solve this in an almost fully automated fashion, using formatting rules that I think result in the most readable file. There is no need for external tools - Eclipse provides everything needed.

  • open up Window->Preferences->XML->XML Files->Editor 
    image
  • check the "Split multiple attributes each on a new line" and adjust other options according to your liking (such as Indent using spaces and Indentation size)
  • press OK to save the options
  • all you have to do now is press Ctrl-Shift-F or select Source->Format

Let's see what this does to the XML I showed above:

image

It's a beauty, isn't it? Eclipse's Auto Format is one of its best features (yes, you can apply it to your Android Java code too as well as pretty much any other document format).

Bonus - XML Cleanup

As an added bonus, Eclipse also offers a Cleanup XML option, which can do the following:

  • compress empty element tags
  • insert required attributes
  • insert missing tags
  • quote attribute values
  • format source (as above)
  • convert line delimiters to Windows, UNIX, or Mac

You can access the Cleanup option via Source->Cleanup

imageRunning Cleanup on my already pretty clean XML file turned the last <item> into this:

image

The first option compressed the <item></item> declaration to simply <item />. Neat, isn't it?

Final Words

+ Clean is good.

+ Uniform is good.

+ Use Ctrl-Shift-F and make it a habit.

+ Create a keyboard shortcut to the Cleanup function by going to Window->Preferences->General->Keys and use it instead of Ctrl-Shift-F (since it already formats as part of the Cleanup).

? I'd like to know if there is a way to apply auto formatting upon save, automatically. Do you?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值