Reputation: 3595
I have a working viewpager example using code I got from a tutorial. The tutorial was written by Lauren Darcey and Shane Conder who are apparently experts (I am new to Android). The code is pasted below. What this code is doing is inflating (ahead) and destroying (behind) as the user swipes horizontally. There are only 5 pages. It seems that it would be much smarter to inflate them all and then let the user do all the swiping with no inflation/destruction going on. Just like it were one big wide page (such as the Panarama and Pivot controls in Windows Phone 7).
Also, this code blows if one of the pages has a google map on it. It blows on the second inflation (don't know why yet) and this wouldn't happen if they were just all inflated once.
Is there a reason why it has to be done this way? Are there any examples available on doing the way I suggest? Thanks, Gary Blakely
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.farleft;
break;
case 1:
resId = R.layout.left;
break;
case 2:
resId = R.layout.middle;
break;
case 3:
resId = R.layout.right;
break;
case 4:
resId = R.layout.farright;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
Upvotes: 2
Views: 4404
Reputation: 67522
You can use ViewPager.setOffscreenPageLimit(int)
to load all off-screen tabs. Just set it to 4
(that's 5 total, minus 1 visible) by doing ((ViewPager) collection).setOffscreenPageLimit(4);
or ((ViewPager) collection).setOffscreenPageLimit(getCount() - 1);
.
Keep in mind the memory implications of this; having everything loaded will run down the device's RAM if you're not careful.
Upvotes: 9