October 24, 2014

Inflation is a Good Thing

Before diving into the topic of creating fancy lists in Android, we need to take a short detour into some background material. If you have written activities for Android, you are used to calling setContentView() with the resource ID of some XML layout you specified. Let’s take a peek at how that is probably implemented: via a technique called “view inflation”.

In this case, “inflation” means the act of converting an XML layout specification into the actual tree of View objects the XML represents. This is undoubtedly a tedious bit of code: take an element, create an instance of the specified View class, walk the attributes, convert those into property setter calls, iterate over all child elements, lather, rinse, repeat.

The good news is that the fine folk on the Android team wrapped all that up into a class called ViewInflate that we can use ourselves. When it comes to fancy lists, for example, we will want to inflate Views for each row shown in the list, so we can use the convenient shorthand of the XML layout to describe what the rows are supposed to look like.

For example, here is your typical do-nothing activity, except re-written to use ViewInflate instead of supplying the resource ID to setContentView():

[sourcecode language='java']
public class InflaterDemo extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(getViewInflate().inflate(R.layout.main, null, null));

// setContentView(R.layout.main);
}
}
[/sourcecode]

Your activity can get an appropriate instance of ViewInflate via getViewInflate(). Then, to convert a resource ID into a View tree, just call inflate() with the resource ID in question. That gives you your View; in this case, we pass the View to setContentView(), as if we had instantiated the View manually.

In our next episodes, we will see how to create fancy rows for the ListView widget, both using manual construction and using view inflation.