Avoid google maps requests until fragment is visible with ViewPager

415 Views Asked by At

I am using ViewPager with three Fragment. One of this fragment (MapFragment) use google maps Api v2.

public class ViewPagerAdapter extends FragmentStatePagerAdapter{

public static final int NUM_PAGES = 3;
public static final int [] titles = {R.string.map, R.string.bus_stop_favorites, R.string.bus_lines};

private Context context;

public ViewPagerAdapter(Context context, FragmentManager fragmentManager) {
    super(fragmentManager);
    this.context = context;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
    case 0:
        return new MapFragment();
    case 1:
        return new FavoritesFragment();         
    case 2:
        return new LinesFragment();     
    default:
        throw new IllegalArgumentException("La posicion fue " + position + " y deberia ser menor a " + NUM_PAGES);
    }
}

@Override
public int getCount() {
    return NUM_PAGES;
}

@Override
public CharSequence getPageTitle(int position) {
    return context.getString(titles[position]);
}

}

When i run my application, i set fragment 1 (FavoriteFragment) like default so it 's the first that i see.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.application_tus);        
    initActionBar();

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setAdapter(new ViewPagerAdapter(this, getSupportFragmentManager()));

    TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titles_viewpager);
    titleIndicator.setViewPager(viewPager,1);
    }
}

MapFragment is sibling of FavoriteFragment so It is loaded when my app start and a Google Map API request is done. However Google Maps API has a limit of quota so I like that MapFragment ONLY do Google Map API request when It is visible and If users don't swipe left , MapFragment doesn't be visible and any request is done.

This image show the three Fragments On ViewPager

enter image description here

1

There are 1 best solutions below

1
On

You could set the offscreen limit of the view pager to 0 so that it only loads the fragment that is currently visible....

http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

EDIT: Apparently, this defaults back to 1 if you set it to 0 so an alternative would be to add a dummy fragment at position 0 (i.e. leftmost fragment) and then dynamically replace it with your map fragment when it becomes visible (using OnPageChangeListener)

http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)