Search code examples
androidlistviewout-of-memorybitmapfactoryrecycle

Thrown out ListView items


I'm currently having problems with a load of thumbnails in my android application. The thumbnails are displayed in list views and I'm wondering if there is a way for me to know which list items are currently in use and stored for faster scrolling, so that I can recycle unused thumbnails if I get a out of memory response from the BitmapFactory.

To be more clear when loading an image into an image view this is really simple but is there a way to observed which items are currently in use or even better a method that is called in a list view when an item is thrown out?

Thanks in advance.


Solution

  • The standard ListView dynamically creates the views of only those items that will be visible. Even if you have more items in your list than fit on the screen there will be no more views than needed to show the items on the screen.

    To list those items that are currently visible on the screen use ListView.getChildAt() and iterate from 0 to ListView.getChildCount(). I.E. do something like this:

    for (int i = 0; i < listView.getChildCount(); i += 1) {
        // the view itself
        View itemView = listView.getChildAt(i);
        // the data it is representing (I used String just as an example)
        String itemData = (String) listView.getItemAtPosition(
                i + listView.getFirstVisiblePosition());
    
        // do whatever you need to do with it
    }
    

    I don't know an easy way to get notified for views that are being recycled. Perhaps you can extend the ListView class and override some methods. Perhaps someone already built a component that has what you need.