ListView items using a Layout defined in XML

To customize the View that an item in a ListView uses (we might want a list item to be organized in some view hierarchy) , an easy approach is to implement a ListActivity, then extend BaseAdapter and call setListAdapter() on an instance of it. BaseAdapter only has a few methods to implement (the most importantly of which is getView(), since this is the method that actually constructs the View for the list item). While there are many examples online of doing this by defining the View programmatically, it took me a long time to discover how to use a Layout defined in res/layouts using XML.

For reference, the solution is to use a LayoutInflater.  Here’s an example

 public View getView(int position, View convertView, ViewGroup parent) {

//here I have stored some strings that I have stored in a SomeObject object, to populate the TextViews defined in my XML layout
//the following methods fetch those values
SomeObject mObject = getItem(position);
String some_string1 = mObject.getSomeString1();
String some_string2 = mObject.getSomeString2();
String some_string3 = mObject.getSomeString3();

//the important step is to get a handle on the LayoutInflater here
LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

//lets us use the XML layout by "inflating" it
 convertView = mInflater.inflate(R.layout.some_layout, parent, false);

//sets the text of the TextViews in the layout

 return convertView;

And there we go! Our ListActivity can now make use of our XML layout to construct the Views of the list items.

This entry was posted in Android and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s