Recent Changes‎ > ‎

New Refactorings: Wrap In, Change Layout, Change Widget

posted Mar 18, 2011, 10:52 AM by Tor Norbye
The ADT now contains a few more refactorings which can be applied either from the layout editor or from the layout XML editor.

First, there is "Change Widget Type":
This lets you select one or more widgets and a new widget type, and it will then change the widgets to use the new widget type instead. In addition to changing the element name, it will also remove any attributes which are not supported by the new widget type, and add in any mandatory attributes required by the new widget type.

In addition, if the current id of the widgets include the current widget type (such as a <Button> widget named "button1"), then the id will be changed to use the new widget type instead (e.g. "imageButton1") and all references updated.

We also have some metadata for which widgets are "related" to each other. So when you bring up the "Change Widget Type" dialog, if you are converting an AnalogClock it will list "DigitalClock" first, and so on.

The second new layout is "Wrap In":
This lets you select one or more sibling elements and wrap them in a new container. This can be applied to the root element as well, in which case the namespace declaration attributes will be transferred to the new root. This refactoring will also transfer layout_ attribute references to the new root, so in for example a RelativeLayout, if other widgets have layout constraints pointing to your widget, wrapping the widget will cause these constraints to point to the parent instead.

This is using the Eclipse refactoring infrastructure, so you get previews of the edits to be performed:

Last, but definitely not least is the new "Change Layout" refactoring.
This refactoring can be applied to any layout view, and will attempt to convert the layout to a new type. In many cases, it does nothing clever - it simply changes the XML element opening and closing tags (and as with the Change Widget Type refactoring, removes unsupported attributes, changes the id attribute and its references, etc). 

However, for some supported types, it attempts to preserve the layout. For example, it can do a pretty decent job converting a LinearLayout to a RelativeLayout. 

Note also the "Flatten Hierarchy" checkbox in the dialog above. This is supported when the target type is a RelativeLayout. This will attempt to not just convert your selected layout, but the entire layout hierarchy under your select, and flatten it into a single target layout! It will skip layouts that have visible artifacts (such as a drawable attribute), and currently only flattens nested LinearLayouts, FrameLayouts and RelativeLayouts. It tries to take layout weights, gravity, order etc. into account.
NOTE - this is still a work in progress - but hopefully gives a useful start for some layouts.