Skip to Content

Fancy ListViews, Part Two

In our last episode, we saw how to create Android ListViews that contain more than just a simple list of strings. In particular, we saw the ultimate form of customization: subclassing an Adapter class, overriding getView(), and returning our own View for each row, perhaps based on our own layout XML inflated via ViewInflate.

As Romain Guy pointed out, though, I left out a piece of the puzzle.

Phones aren't the speediest things out there. In Android, creating widgets (Views) is a comparatively expensive operation, not to mention the garbage collection of getting rid of them once you're done. Hence, you don't want to create any more widgets than you have to.

Now, let's imagine we have a ListView that, on-screen, can show 7 entries, but the list itself has 50 entries, perhaps from a database or some parsed Internet content. Creating widgets for 7 entries is much less expensive than creating widgets for 50 entries. Yet, our getView() implementation from the last post will create widgets whenever it is asked. If you add Log statements to see what happens, you will see that, if you scroll through the whole list, you will be called 50 times.

Urk!

Android has a way to help you improve your getView() performance; as Romain Guy indicated, it's via the contentView parameter passed into getView().

Sometimes, convertView will be null. In those cases, you have to create a new row View from scratch (e.g., via inflation), just as we did before.

However, if convertView is not null, then it is actually one of your previously-created Views! This will happen primarily when the user scrolls the ListView -- as new rows appear, Android will attempt to recycle the views of the rows that scrolled off the other end of the list, to save you having to rebuild them from scratch.

Assuming that each of your rows has the same basic structure, you can use findViewById() to get at the individual widgets that make up your row and change their contents, then return contentView from getView(), rather than create a whole new row.

For example, here is the getView() implementation from last time, now optimized via contentView:

[sourcecode language='java']
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;

if (row==null) {
ViewInflate inflater=context.getViewInflate();

row=inflater.inflate(R.layout.row, null, null);
}

TextView label=(TextView)row.findViewById(R.id.label);

label.setText(items[position]);

if (items[position].length()>4) {
ImageView icon=(ImageView)row.findViewById(R.id.icon);

icon.setImageResource(R.drawable.delete);
}

return(row);
}
[/sourcecode]

Here, we check to see if the contentView is null and, if so, we then inflate our row -- but if it is not-null, we just reuse it. The work to fill in the contents (icon image, text) is the same in either case. The advantage is that we avoid the potentially-expensive inflation step.

This approach will not work in every case, though. For example, the TourIt sample application in my book uses a ListView to show the cue sheet for a bicycle tour. Think of a cue sheet as Google Map directions, but hand-written to deal with idiosyncracies of cycling (e.g., avoiding nasty intersections). Each row in the cue sheet represents one step in the directions (e.g., ride 0.5 miles and turn left onto Mosser Blvd.).

However, some steps in the cue sheet have additional notes (e.g., "high traffic area!"). So all this can be readable, sometimes TourIt uses a single line of text (plus icons) in the row, and sometimes two lines of text, as shown below:

In this case, recycling existing rows becomes tricky, as the layouts may significantly differ. For example, if the row we need to create a View for requires two lines of text, we cannot just use a View with one line of text as-is. We either need to tinker with the innards of that View, or ignore it and inflate a new View.

Of course, there are ways to deal with this, such as making the second line of text visible or invisible depending on whether it is needed. And, on a phone, every millisecond of CPU time is precious, possibly for the user experience, but always for battery life -- more CPU utilization means a more quickly-drained battery.

That being said, particularly if you are a rookie to Android, I recommend focusing on getting the functionality right first, then looking to optimize performance on a second pass through your code, rather than get lost in a sea of Views trying to tackle it all in one shot.

Might We Suggest...

  • Fancy ListViews Redux: 0.9 SDK and RatingBar
    You may remember way back when (e.g., July 2008) when Building 'Droids featured a six-post series on creating fancy ListView implementations, culminating in a CheckListView widget that could be used a...

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

4 Responses to “Fancy ListViews, Part Two” Leave a reply ›

  • Mark, you mentioned about recycling existing rows are tricky and indeed it is tricky... especially when the layout in rows are different.. can you provide some sample on how to handle this? im having a hard time figuring it out. I have some part of my list that needs only one textview and the remaining have 2 textview. What i did is I set that textview to invisible or gone. Others row were rendered correctly but when i scrolled down and reached a row with only one textview, some rows that is supposed to have 2 textview became 1.

    Can you help?? thanks..

  • for God sake! please fix the source code on these ListViews posts!

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

We allow third-party companies to serve ads and/or collect certain anonymous information when you visit our web site. These companies may use non-personally identifiable information (e.g., click stream information, browser type, time and date, subject of advertisements clicked or scrolled over) during your visits to this and other Web sites in order to provide advertisements about goods and services likely to be of greater interest to you. These companies typically use a cookie or third party web beacon to collect this information. To learn more about this behavioral advertising practice or to opt-out of this type of advertising, you can visit www.networkadvertising.org.