Mallika Khullar
Mallika Khullar

Reputation: 1813

ViewPager setCurrentItem(n, false) calls instantiateItem multiple times - Android

I have a ViewPager in which each page shows loads a full screen image using UniversalImageLoader and an image URL.

I'm using viewPager.setCurrentItem(n, false) to open the ViewPager to any image and not always the first image.

The problem is, when I call viewPager.setCurrentItem(n, false), it calls instantiateItem (n+1) times and the universal image loader loads all those (n+1) images which is inefficient for me.

I want my ViewPager to set the current item to (n) and only instantiate the preceding and following pages. Is it possible?

Upvotes: 1

Views: 999

Answers (2)

Jeffalee
Jeffalee

Reputation: 1085

According to the Android documentation, the use of setCurrentItem(int position, boolean smoothScroll) and setCurrentItem(int position) will scroll the ViewPager to the given position. Therefore all the views that will be scrolled through will be loaded. So you shouldnt call that method if you dont want to load all those views.

Instead you could try to adjust the positions of the items in your List you use for your PagerAdapter. So instead of scrolling the ViewPager to position 5, you could try to move the item at position 5 in your List to position 0 and then update the PagerAdapter. You could for example remove the first 4 items and place them at the end, this will reduce the amount of views that have to be loaded. But I dont know if that meets your requirements.

Upvotes: 0

Reza.Abedini
Reza.Abedini

Reputation: 2257

try this :

yourViewPager.setOffscreenPageLimit(1);

and then your view pager just loads (n-1) , (n) and (n+1) pages.\ also if you use fragments in your view pager you can force it to load fragment #n by something like this:

public class MyFragment extends Fragment {
  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        //Load your image
      }
        else {  }
      }
    }

Upvotes: 1

Related Questions