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.

About author

AndroidGuys
AndroidGuys 4625 posts

Founded on November 5, 2007, we've enjoyed bringing you the latest in Android news and rumors. Updated daily, we strive to deliver reviews, opinions, and updates on all things related to Android.

You might also like

News and Rumors

Google removes silent mode from phones with Lollipop

Android 5.0 Lollipop brings a lot of new features and a whole new look with the material design makeover, but it seems that the update also removes the ability to

News and Rumors

Everything We Know About the Nexus One – And a Few Things We Still Don’t [UPDATED]

We know there’s a lot to keep up with in regardds to the Nexus One so we’ve tasked ourselves with compiling all the known and rumored information.  Below, you’ll find

News and Rumors

LG Optimus S Coming to Sprint November 7

Today Sprint announced (re-announced) the upcoming LG Optimus S.  The Optimus S was originally announced about a month ago at CTIA, and was suppose to be on the shelves on