Home > android, ui > Redrawing a ListView

Redrawing a ListView

I had a ListView that needed to be completely redrawn when the user changed the sort order.

Tried calling listView.invalidate() – that didn’t work.

After thinking about it for a bit, I realized this is correct. Here is why.

A ListView creates a view hierarchy to display individual items. This is done by calling getView(…) in the ListView’s adapter. These views are kept around for as long as they are within the ListView’s visible area.

What invalidate() does is forces a redraw of the ListView, including its view hierarchy. This is roughly the same as the view being exposed after being obscured by some other view.

However, the view hierarchy stays the same, so the view’s appearance does not change.

The correct way is this: update the data in memory (to reflect sort order, or whatever) and call listView.setAdapter().

This makes the ListView dispose of the old view hierarchy, and create it over again. Since the data was sorted prior to calling setAdapter(), the new view hierarchy will reflect the new order.

Categories: android, ui
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s