Question

I have a ListView that loads images to the ImageView asynchronously. To achieve this i am using Android-Universal-Image-Loader

But i would like to start loading this images only when they are visible in the listview. For example if the visible items of the listview are from 5 to 9, only those should be loaded. Also if the user scrolls very fast the ListView only when stopped those items should be loaded. What is the best way to this?

Was it helpful?

Solution

If you use "view reusing" in your listview adapter then you shouldn't do anything. UIL do it for you. UIL won't load ALL scrolled images, only those which are got in task pool (you can set set pool size in configuration). If you use "view reusing" then images which were scrolled fast won't be loaded. Look into example project on GitHub.

UPD: Since 1.7.0 version UIL have PauseOnScrollListener.

boolean pauseOnScroll = true;
boolean pauseOnFling = true;
listView.setOnScrollListener(new PauseOnScrollListener(pauseOnScroll, pauseOnFling));

OTHER TIPS

Use an OnScrollListener, the onScrollStateChanged() method is called when the ListView switches between SCROLL_STATE_IDLE, SCROLL_STATE_TOUCH_SCROLL (slower scrolling), and SCROLL_STATE_FLING (faster scrolling). With this you can choose to load new images only when the states is "Idle" or "Touch".


Addition

In the first run the visible items of the ListView aren't shown. For example when the app starts if the ListView has 4 items visible those 4 images should be loaded.

I haven't used the Universal Image Loader myself, but from what you described below you need to know how many rows will be displayed before you start downloading. Try this:

  • Write a Runnable to start the asynchronous downloads.
  • Use your ListView's built-in Handler to call the Runnable after the rows have been drawn

For example:

private Runnable loadImages = new Runnable() {
    @Override
    public void run() {
        // Start the asynchronous downloads
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    mListView.post(loadImages);
}

The loadImages will be called after the ListView is drawn so you will know exactly how many rows are visible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top